package com.java.test.a; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class ReadAndWriteTXT { public static String resolveCode(String path) throws Exception { InputStream inputStream = new FileInputStream(path); byte[] head = new byte[3]; inputStream.read(head); String code = "gb2312"; //或GBK if (head[0] == -1 && head[1] == -2 ) code = "UTF-16"; else if (head[0] == -2 && head[1] == -1 ) code = "Unicode"; else if(head[0]==-17 && head[1]==-69 && head[2] ==-65) code = "UTF-8"; inputStream.close(); return code; } public static void main(String[] args) { /**读取txt文件*/ String pathname = "D:/test.txt"; // 绝对路径或相对路径都可以,这里是绝对路径 String code = ""; try { code = resolveCode(pathname);//获取txt文档编码 } catch (Exception e1) { e1.printStackTrace(); } File filename = new File(pathname); //读取文件 InputStreamReader reader = null; BufferedReader br = null; try { try { reader = new InputStreamReader(new FileInputStream(filename),code); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //输入流 br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言 } catch (FileNotFoundException e) { e.printStackTrace(); } try { String line = ""; while ((line = br.readLine()) != null) { // line = br.readLine(); // 一次读入一行数据 System.out.println(line); } } catch (IOException e) { System.out.println("文件读取错误"); } //在写入文件时,若没有找到目标文件,则会创建一个 /**写入txt文件*/ File writename = new File(".\file\output.txt"); //相对路径,以项目文件为根路径:Test/file/output.txt BufferedWriter out = null; try { writename.createNewFile(); // 创建新文件 out = new BufferedWriter(new FileWriter(writename)); out.write("写入文件测试 第二行 第三行 nqwertyuiop 1234567890"); // 即为换行 out.flush(); // 把缓存区内容压入文件 out.close(); // 关闭输出 } catch (IOException e) { System.out.println("文件输入错误"); e.printStackTrace(); } } }
相对路径:
在使用相对路径读取和写入文件时,相对项目根目录Test进行读取,例如:./file/output.txt,完整路径为D:/workspace/Test/file/output.txt