java中文件读和写的操作

原创
2016/04/09 22:03
阅读数 65

import java.io.*;

//文件读

class FileReadTest {     
  public static void main (String[] args) {
    FileReadTest t = new FileReadTest();
    t.readMyFile();
}
   
  void readMyFile() {
    String record = null;
    int recCount = 0;
    try {
FileReader fr = new FileReader("mydata.txt");
       BufferedReader br = new BufferedReader(fr);
       record = new String();
       while ((record = br.readLine()) != null) {
         recCount++;
         System.out.println(recCount + ": " + record);
}
br.close();
fr.close();
     } catch (IOException e) {
         System.out.println("Uh oh, got an IOException error!");
         e.printStackTrace();
     }
}
 
}

 

 

///////////////////////////////////////////////////

//文件写

import java.io.*;

class FileWriteTest {     
  public static void main (String[] args) {
    FileWriteTest t = new FileWriteTest();
    t.WriteMyFile();
}
   
  void WriteMyFile() {
    try {
FileWriter fw = new FileWriter("mydata.txt");
PrintWriter out = new PrintWriter(fw);   
out.print(“hi,this will be wirte into the file!”);  
out.close();
fw.close();
     } catch (IOException e) {
         System.out.println("Uh oh, got an IOException error!");
         e.printStackTrace();
     }
}
 
}

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
1 收藏
1
分享
返回顶部
顶部