Java文件操作 读写操作

时间:2024-03-07 13:30:01

一、Java读取文件

案例1:读取D盘的1.txt文件

                                             

编码:

 1 File file = new File("D:/1.txt");
 2         FileReader fr = new FileReader(file);
 3         BufferedReader bf = new BufferedReader(fr);
 4         StringBuffer sbuffer = new StringBuffer();
 5         String temp = null;
 6         while((temp = bf.readLine()) !=null){
 7             sbuffer.append(temp+"\n");
 8         }
 9         System.out.println(sbuffer.toString());
10         
11         System.out.println();

结果:

二、写入文件

案例:讲D盘中的1.txt文件内容写入D盘一个2.txt文件。

编码:

 1 File file = new File("D:/1.txt");
 2         FileReader fr = new FileReader(file);
 3         BufferedReader bf = new BufferedReader(fr);
 4         StringBuffer sbuffer = new StringBuffer();
 5         String temp = null;
 6         while((temp = bf.readLine()) !=null){
 7             sbuffer.append(temp+"\n");
 8         }
 9         System.out.println(sbuffer.toString());
10         
11         System.out.println();
12         File outfile = new File("D:/2.txt");
13         if(!outfile.exists()){
14             try {
15                 outfile.createNewFile();
16             } catch (IOException e) {
17                 // TODO Auto-generated catch block
18                 e.printStackTrace();
19             }
20         }
21         byte[] b = (sbuffer.toString()).getBytes();
22         FileOutputStream fs = null;
23         fs = new FileOutputStream(outfile);
24         fs.write(b);
25         
26         fs.close();
27         bf.close();    
28