Java初学者笔记四:按行读写文件和输入处理 - 土拨鼠数据合规与安全
2018-3-12 17:13:0 Author: www.cnblogs.com(查看原文) 阅读量:5 收藏

一、我们来看python的很简单:

1、读文件:

1 with open("/path/file","r") as fr:
2     for line in fr.readlines():
3         do_somethings(line)

2、写文件:

1 with open("/path/file","w/a") as fr:
2     fr.write("ssssssss")

二、上文知识一个引子,不是重点,还是来学习java的文件读写操作吧:

最常用的还是按行读写,当然后面也会带一点其他读写方法:

1、按行读取:

1 File file = new File("绝对路径");
2 BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
3 String str = null;
4 while((str = bufferedReader.readLine()) != null)  
5 {  
6     System.out.println(str);  
7 }
8 bufferedReader.close();

2、按行写入:

1 FileWriter filew = new FileWriter("绝对路径",true);
2 //true表示追加,否则是覆盖写,覆盖写不需要true
3 filew.write("\ntest\n");
4 filew.close();
1 List<String> b = Files.readAllLines(Paths.get("/Users/a003797/Desktop/a1.txt"));
2 for(String item:b) {
3     System.out.println(item)    ;    
4 }

3、其他读取方式:

1 //读取全部字节:
2 byte[] a = Files.readAllBytes(Paths.get("/Users/a003797/Desktop/a1.txt"));

三、输入处理

 1 import java.io.*;
 2 
 3 public class test{
 4     public static void main(String args[]) throws IOException {
 5         BufferedReader br =  new BufferedReader(new InputStreamReader(System.in));    
 6         while(true){
 7             String string = br.readLine();
 8             System.out.println(string);
 9         }
10     }
11 }

文章来源: https://www.cnblogs.com/KevinGeorge/p/8550374.html
如有侵权请联系:admin#unsafe.sh