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; { //使用readLine方法,一次讀一行 |