java 对txt文件读写(已经封装好)
读文件:
1 public static String readTxt(String txtPath) { 2 File file = new File(txtPath); 3 if(file.isFile() && file.exists()){ 4 try { 5 FileInputStream fileInputStream = new FileInputStream(file); 6 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); 7 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 8 9 StringBuffer sb = new StringBuffer(); 10 String text = null; 11 while((text = bufferedReader.readLine()) != null){ 12 sb.append(text); 13 } 14 return sb.toString(); 15 } catch (Exception e) { 16 e.printStackTrace(); 17 } 18 } 19 return null; 20 }
写文件:
1 public static void writeTxt(String txtPath,String content){ 2 FileOutputStream fileOutputStream = null; 3 File file = new File(txtPath); 4 try { 5 if(file.exists()){ 6 //判断文件是否存在,如果不存在就新建一个txt 7 file.createNewFile(); 8 } 9 fileOutputStream = new FileOutputStream(file,true);//多个true就是追加 10 fileOutputStream.write(content.getBytes()); 11 fileOutputStream.flush(); 12 fileOutputStream.close(); 13 } catch (Exception e) { 14 e.printStackTrace(); 15 } 16 }
完整代码:
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.InputStreamReader; 6 public class 文件读写 { 7 public static String readTxt(String txtPath) { 8 File file = new File(txtPath); 9 if(file.isFile() && file.exists()){ 10 try { 11 FileInputStream fileInputStream = new FileInputStream(file); 12 InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); 13 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 14 15 StringBuffer sb = new StringBuffer(); 16 String text = null; 17 while((text = bufferedReader.readLine()) != null){ 18 sb.append(text); 19 } 20 return sb.toString(); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } 24 } 25 return null; 26 } 27 public static void writeTxt(String txtPath,String content){ 28 FileOutputStream fileOutputStream = null; 29 File file = new File(txtPath); 30 try { 31 if(file.exists()){ 32 //判断文件是否存在,如果不存在就新建一个txt 33 file.createNewFile(); 34 } 35 fileOutputStream = new FileOutputStream(file,true);//多个true就是追加 36 fileOutputStream.write(content.getBytes()); 37 fileOutputStream.flush(); 38 fileOutputStream.close(); 39 } catch (Exception e) { 40 e.printStackTrace(); 41 } 42 } 43 }