java文件讀寫的問題,java 文件讀寫

本文目錄一覽:

Java文件讀寫

實用的模糊(通配符)文件查找程序

1 import java.io.File;

2 import java.util.regex.Matcher;

3 import java.util.regex.Pattern;

4 import java.util.ArrayList;

5

6 /** *//**

7 * pTitle: FileService /p 8* pDescription: 獲取文件 /p 9* pCopyright: Copyright (c) 2007/p

10* pCompany: /p

11* @author not attributable

12* @version 1.0

13*/

14public class FileService {

15 public FileService() {

16 }

17

18 /** *//**

19 * 在本文件夾下查找

20 * @param s String 文件名

21 * @return File[] 找到的文件

22 */

23 public static File[] getFiles(String s)

24 {

25 return getFiles(“./”,s);

26 }

27

28 /** *//**

29 * 獲取文件

30 * 可以根據正則表達式查找

31 * @param dir String 文件夾名稱

32 * @param s String 查找文件名,可帶*.?進行模糊查詢

33 * @return File[] 找到的文件

34 */

35 public static File[] getFiles(String dir,String s) {

36 //開始的文件夾

37 File file = new File(dir);

38

39 s = s.replace(‘.’, ‘#’);

40 s = s.replaceAll(“#”, “\\\\.”);

java讀取寫入文件問題

java 追加內容到文件末尾的幾種常用方法

import java.io.FileWriter;

import java.io.IOException;

import java.io.RandomAccessFile;

public class AppendToFile {

/**

* A方法追加文件:使用RandomAccessFile

*/

public static void appendMethodA(String fileName, String content) {

try {

// 打開一個隨機訪問文件流,按讀寫方式

RandomAccessFile randomFile = new RandomAccessFile(fileName, “rw”);

// 文件長度,位元組數

long fileLength = randomFile.length();

//將寫文件指針移到文件尾。

randomFile.seek(fileLength);

randomFile.writeBytes(content);

randomFile.close();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* B方法追加文件:使用FileWriter

*/

public static void appendMethodB(String fileName, String content) {

try {

//打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件

FileWriter writer = new FileWriter(fileName, true);

writer.write(content);

writer.close();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

String fileName = “E:/newTemp.dat”;

String content = “new append!”;

//按方法A追加文件

AppendToFile.appendMethodA(fileName, content);

AppendToFile.appendMethodA(fileName, “append end.”);

//顯示文件內容

ReadFromFile.readFileByBytes(fileName);//.readFileByLines(fileName);

/* //按方法B追加文件

AppendToFile.appendMethodB(fileName, content);

AppendToFile.appendMethodB(fileName, “append end. \n”);

//顯示文件內容

ReadFromFile.readFileByBytes(fileName);*/

// ReadFromFile.readFileByLines(fileName);

}

}

java 文件讀寫問題

看你兩個截圖 是要往文件裡面加一個數25

但是你描述的是讀一個 數出來 加上25 然後再寫入文件。。。。需求說清楚

JAVA的文件讀寫問題

當熱身了~import java.io.BufferedWriter;

import java.io.FileWriter;

import java.util.*;/*編寫一個程序,用於從鍵盤讀入信息,並存儲到磁碟文件中去。

要求:1. 以行的方式讀入姓名和學號信息,例如:張三 20071215 (姓名和學號中間用一個空格隔開)

2. 循環讀入,直到用戶輸入「quit」或者「QUIT」結束

3. 程序提示要用戶輸入一個文件名,例如:請輸入存儲到的文件名: userlist.txt

4. 在整個上述過程中,要做例外處理;如果文件創建成功,則給出提示信息。*/public class test9

{

public static void main(String[] args)

{

T1();

}

public static void T1()

{

FileWriter out ;

BufferedWriter bw;

String fileName = null;

String message = null;

Scanner scanner = new Scanner(System.in);

System.out.print(“請輸入存儲到的文件名:”);

fileName = scanner.next();

try

{

out = new FileWriter(fileName);

bw = new BufferedWriter(out);

System.out.print(“\n文件創建成功!\n請輸入姓名和學號信息:”);

while( !(message = scanner.next()).equalsIgnoreCase(“quit”))

{

bw.write(message);

bw.newLine();

}

bw.close();

out.close();

}

catch(Exception e)

{

System.out.println(“文件創建失敗!”);

}

}} import java.util.Scanner;

import java.io.*;/*再編寫一個程序,用於從上述存儲的磁碟文件中讀出信息,並顯示在屏幕上。

要求:

1)文件名從鍵盤輸入;

2)姓名和學號分開顯示,例如屏幕顯示如下信息:

文件 userlist.txt 中存儲的姓名有: 張三 李四王五 ……

文件userlist.txt 中存儲的學號有: 20061215 20061317 20061425 ….. */

public class test10

{

public static void main(String[] args)

{

T2();

}

public static void T2()

{

FileReader read;

BufferedReader in ;

Scanner scanner = new Scanner(System.in);

String fileName = null;

String message = null;

String[] buf = new String[2];

String[] name = new String[10];

String[] number = new String[10];

int pos1 = 0;

int pos2 = 0;

System.out.print(“請輸入要讀取的文件名:”);

fileName = scanner.next();

try

{

read = new FileReader(fileName);

in = new BufferedReader(read);

while((message = in.readLine()) != null)

{

buf = message.split(” “);

name[pos1++] = buf[0];

number[pos2++] = buf[1];

buf = new String[2];

}

}

catch(Exception e)

{

System.out.println(“該文件不存在!”);

}

System.out.println( “屏幕顯示如下信息:”);

System.out.print(“文件”+fileName+”中存儲的姓名有:”);

for(int i = 0; name[i] != null;i++)

{

System.out.print(name[i]+” “);

}

System.out.print(“\n文件”+fileName+”中存儲的學號有:”);

for(int i = 0; number[i] != null;i++)

{

System.out.print(number[i]+” “);

}

}}

java 讀寫文件異常怎麼處理

public class ReadFromFile {

    /**

     * 以位元組為單位讀取文件,常用於讀二進位文件,如圖片、聲音、影像等文件。

     */

    public static void readFileByBytes(String fileName) {

        File file = new File(fileName);

        InputStream in = null;

        try {

            System.out.println(“以位元組為單位讀取文件內容,一次讀一個位元組:”);

            // 一次讀一個位元組

            in = new FileInputStream(file);

            int tempbyte;

            while ((tempbyte = in.read()) != -1) {

                System.out.write(tempbyte);

            }

            in.close();

        } catch (IOException e) {

            e.printStackTrace();

            return;

        }

        try {

            System.out.println(“以位元組為單位讀取文件內容,一次讀多個位元組:”);

            // 一次讀多個位元組

            byte[] tempbytes = new byte[100];

            int byteread = 0;

            in = new FileInputStream(fileName);

            ReadFromFile.showAvailableBytes(in);

            // 讀入多個位元組到位元組數組中,byteread為一次讀入的位元組數

            while ((byteread = in.read(tempbytes)) != -1) {

                System.out.write(tempbytes, 0, byteread);

            }

        } catch (Exception e1) {

            e1.printStackTrace();

        } finally {

            if (in != null) {

                try {

                    in.close();

                } catch (IOException e1) {

                }

            }

        }

    }

  

    /**

     * 以字元為單位讀取文件,常用於讀文本,數字等類型的文件

     */

    public static void readFileByChars(String fileName) {

        File file = new File(fileName);

        Reader reader = null;

        try {

            System.out.println(“以字元為單位讀取文件內容,一次讀一個位元組:”);

            // 一次讀一個字元

            reader = new InputStreamReader(new FileInputStream(file));

            int tempchar;

            while ((tempchar = reader.read()) != -1) {

                // 對於windows下,\r\n這兩個字元在一起時,表示一個換行。

                // 但如果這兩個字元分開顯示時,會換兩次行。

                // 因此,屏蔽掉\r,或者屏蔽\n。否則,將會多出很多空行。

                if (((char) tempchar) != ‘\r’) {

                    System.out.print((char) tempchar);

                }

            }

            reader.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

        try {

            System.out.println(“以字元為單位讀取文件內容,一次讀多個位元組:”);

            // 一次讀多個字元

            char[] tempchars = new char[30];

            int charread = 0;

            reader = new InputStreamReader(new FileInputStream(fileName));

            // 讀入多個字元到字元數組中,charread為一次讀取字元數

            while ((charread = reader.read(tempchars)) != -1) {

                // 同樣屏蔽掉\r不顯示

                if ((charread == tempchars.length)

                         (tempchars[tempchars.length – 1] != ‘\r’)) {

                    System.out.print(tempchars);

                } else {

                    for (int i = 0; i  charread; i++) {

                        if (tempchars[i] == ‘\r’) {

                            continue;

                        } else {

                            System.out.print(tempchars[i]);

                        }

                    }

                }

            }

  

        } catch (Exception e1) {

            e1.printStackTrace();

        } finally {

            if (reader != null) {

                try {

                    reader.close();

                } catch (IOException e1) {

                }

            }

        }

    }

  

    /**

     * 以行為單位讀取文件,常用於讀面向行的格式化文件

     */

    public static void readFileByLines(String fileName) {

        File file = new File(fileName);

        BufferedReader reader = null;

        try {

            System.out.println(“以行為單位讀取文件內容,一次讀一整行:”);

            reader = new BufferedReader(new FileReader(file));

            String tempString = null;

            int line = 1;

            // 一次讀入一行,直到讀入null為文件結束

            while ((tempString = reader.readLine()) != null) {

                // 顯示行號

                System.out.println(“line ” + line + “: ” + tempString);

                line++;

            }

            reader.close();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (reader != null) {

                try {

                    reader.close();

                } catch (IOException e1) {

                }

            }

        }

    }

  

    /**

     * 隨機讀取文件內容

     */

    public static void readFileByRandomAccess(String fileName) {

        RandomAccessFile randomFile = null;

        try {

            System.out.println(“隨機讀取一段文件內容:”);

            // 打開一個隨機訪問文件流,按只讀方式

            randomFile = new RandomAccessFile(fileName, “r”);

            // 文件長度,位元組數

            long fileLength = randomFile.length();

            // 讀文件的起始位置

            int beginIndex = (fileLength  4) ? 4 : 0;

            // 將讀文件的開始位置移到beginIndex位置。

            randomFile.seek(beginIndex);

            byte[] bytes = new byte[10];

            int byteread = 0;

            // 一次讀10個位元組,如果文件內容不足10個位元組,則讀剩下的位元組。

            // 將一次讀取的位元組數賦給byteread

            while ((byteread = randomFile.read(bytes)) != -1) {

                System.out.write(bytes, 0, byteread);

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (randomFile != null) {

                try {

                    randomFile.close();

                } catch (IOException e1) {

                }

            }

        }

    }

  

    /**

     * 顯示輸入流中還剩的位元組數

     */

    private static void showAvailableBytes(InputStream in) {

        try {

            System.out.println(“當前位元組輸入流中的位元組數為:” + in.available());

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

  

    public static void main(String[] args) {

        String fileName = “C:/temp/newTemp.txt”;

        ReadFromFile.readFileByBytes(fileName);

        ReadFromFile.readFileByChars(fileName);

        ReadFromFile.readFileByLines(fileName);

        ReadFromFile.readFileByRandomAccess(fileName);

    }

}

Java文件讀寫問題

第一 寫完文件後,建議進行一次flush

第二 你的main方法中: new test(); 此語句只是創建一個Test的對象並沒有執行test()方法,改為 new test().test();

第三 調試階段,建議你將Exception的信息列印出來.

不謝.

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/283465.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-22 08:08
下一篇 2024-12-22 08:08

相關推薦

發表回復

登錄後才能評論