java读写文本文件
接触java有很长一段时间,越来越能体会到语言真的只是一种工具,经常利用java对数据进行清洗,所以最经常用的功能就是文本的读取和写入,但是这最最基本的用法我却用的不熟练,每次用都要翻之前的project,现在特意贴在这边,也方便自己查找。
1、读取文本文件
1 public static void read(String fp) throws IOException{ 2 try { 3 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fp))); 4 String data=""; 5 while((data=br.readLine())!=null){ 6 System.out.println(data); 7 8 } 9 } catch (FileNotFoundException e) { 10 // TODO Auto-generated catch block 11 e.printStackTrace(); 12 } 13 14 }
2.一种覆盖性写入的代码
1 import java.io.File; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4 import java.io.PrintStream; 5 6 /** 7 * @author 8 9 */ 10 public class WriteTxtFileByName { 11 private String filename = null; 12 13 public WriteTxtFileByName(String filename) { 14 this.filename = filename; 15 } 16 17 public void writeFileByName(String content) { 18 File docFile = new File(filename); 19 try { 20 docFile.createNewFile(); 21 FileOutputStream txtfile = new FileOutputStream(docFile); 22 PrintStream p = new PrintStream(txtfile); 23 p.println(content); 24 txtfile.close(); 25 p.close(); 26 } catch (IOException e) { 27 e.printStackTrace(); 28 } 29 } 30 31 public static void main(String[] args) { 32 WriteTxtFileByName wfbn = new WriteTxtFileByName("e:/title.txt"); 33 wfbn.writeFileByName("content"); 34 wfbn.writeFileByName("title"); 35 wfbn.writeFileByName("label"); 36 } 37 }
3.写入数据
import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; /** * @author */ public class WriteTxtFileByName { public static void writeFileByName(String fp) { try{ FileWriter fileWriter=new FileWriter(fp); fileWriter.write("*Vertices "+7);//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! fileWriter.write("\n");//!!!!!!!!!!!!!!!! fileWriter.write("*Matrix");//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! fileWriter.flush(); fileWriter.close(); }catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args) { writeFileByName("e:/title.txt"); } }