Java 创造txt文件与读写内容
Java 创建txt文件与读写内容
package com.broadtext.eim.test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; /** * * TODO 此处为类的功能性说明 * @Time 下午06:28:41 * @author mengjiahao */ public class WriteTextService { public static BufferedReader bufread; // 指定文件路径和名称 private static String path = "D:/sessionId.txt"; private static File filename = new File(path); private static String readStr = ""; /** */ /** * 创建文本文件. * * @throws IOException * */ public static void creatTxtFile() throws IOException { if (!filename.exists()) { filename.createNewFile(); System.err.println(filename + "已创建!"); } } /** */ /** * 读取文本文件. * * @throws IOException * */ public static String readTxtFile() throws IOException { String strs = ""; try { FileReader read = new FileReader(filename); StringBuffer sb = new StringBuffer(); char ch[] = new char[1024]; int d = read.read(ch); while (d != -1) { String str = new String(ch, 0, d); sb.append(str); d = read.read(ch); } strs = sb.toString(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("文件内容是:" + "\r\n" + strs); return strs; } /** */ /** * 写文件. * */ public static void writeTxtFile(String newStr) throws IOException { // 创建文件 creatTxtFile(); // 读取文件 String str = readTxtFile(); // 写入文件 FileWriter fw = new FileWriter(path); if (str.length() < 1) { fw.write(newStr); } else { fw.write(str + "\r\n" + newStr); } fw.close(); } /** */ /** * 将文件中指定内容的第一行替换为其它内容. * * @param oldStr * 查找内容 * @param replaceStr * 替换内容 */ public static void replaceTxtByStr(String oldStr, String replaceStr) { String temp = ""; try { File file = new File(path); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); StringBuffer buf = new StringBuffer(); // 保存该行前面的内容 for (int j = 1; (temp = br.readLine()) != null && !temp.equals(oldStr); j++) { buf = buf.append(temp); buf = buf.append(System.getProperty("line.separator")); } // 将内容插入 buf = buf.append(replaceStr); // 保存该行后面的内容 while ((temp = br.readLine()) != null) { buf = buf.append(System.getProperty("line.separator")); buf = buf.append(temp); } br.close(); FileOutputStream fos = new FileOutputStream(file); PrintWriter pw = new PrintWriter(fos); pw.write(buf.toString().toCharArray()); pw.flush(); pw.close(); } catch (IOException e) { e.printStackTrace(); } } /** */ /** * main方法测试 * * @param s * @throws IOException */ public static void main(String[] s) throws IOException { // 创建文件 creatTxtFile(); // 读取文件 readTxtFile(); // 写入文件 writeTxtFile("道是无晴却有晴"); // 读取文件 readTxtFile(); } }