1. 程式人生 > >Java實現在文字檔案中寫入資料和讀取資料

Java實現在文字檔案中寫入資料和讀取資料

Java實現在文字檔案中寫入資料和讀取資料

寫資料到文字檔案中去:

程式碼如下所示:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
    public static void main(String[] args) {
        File file = null;
        FileWriter fw = null;
        file = new File("F:\\JMeterRes\\Data\\test123.txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            for(int i = 1;i <=3000;i++){
            fw.write("abcdefgabcdefg"+i+",");              //向檔案中寫內容
            fw.write("sssssssssssssss"+i+",\r\n");        //加上換行
            fw.flush();
            }
            System.out.println("寫資料成功!");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(fw != null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
 

從文字檔案中讀取資料:

程式碼如下所示:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
 
public class ReadFiledata {
    public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));        //構造一個BufferedReader類來讀取檔案
            String s = null;
            while((s = br.readLine())!=null)

            {

                //使用readLine方法,一次讀一行
                result.append(System.lineSeparator()+s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
    public static void main(String[] args){
        File file = new File("F:/JMeterRes/Data/test123.txt");
        System.out.println(txt2String(file));
    }
}