一、我们来看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 }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; min-height: 15.0px }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #931a68 }
span.s1 { color: #931a68 }
span.s2 { color: #000000 }
span.s3 { color: #7e504f }
span.s4 { color: #0326cc }
span.Apple-tab-span { white-space: pre }
原文地址:https://www.cnblogs.com/KevinGeorge/p/8550374.html
时间: 2024-11-05 12:24:38