标签:
package file; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.Writer; import java.util.Scanner; /** * * @author Administrator * */ public class FileUtil { public static void main(String args[]) { String srcFile = "D:/old.txt"; String toFile = "D:/new.txt"; try { String result = read(srcFile); write(result, toFile); } catch (Exception e) { e.printStackTrace(); } } private static String read(String srcFile) throws FileNotFoundException { Scanner in = new Scanner(new File(srcFile)); String result = ""; while (in.hasNextLine()) { result += in.nextLine() + "\r\n"; } in.close(); return result; } private static void write(String result, String toFile) throws Exception { Writer w = new FileWriter(new File(toFile)); w.write(result); w.flush(); w.close(); } }
追加文件
package file; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; import java.io.Writer; /** * 两种方法 * 追加文件 * @author Administrator * */ public class AppendFile { public static void Append1() throws IOException{ String content="---第一种方法添加文件内容-------\r\n6666"; Writer w = new FileWriter(new File("new.txt"),true); w.append(content); System.out.println("追加成功"); String c1="1q1q\r\n"; w.append(c1); w.flush(); w.close(); } public static void Append2() throws IOException{ RandomAccessFile randomFile = new RandomAccessFile(new File("D://new.txt"), "rw"); // 文件长度,字节数 long fileLength = randomFile.length(); //将写文件指针移到文件尾。 randomFile.seek(fileLength); randomFile.writeBytes("00000xxxxxxxx11111"); randomFile.close(); } public static void main(String[] args) throws IOException { Append1(); Append2(); } }
标签:
原文地址:http://www.cnblogs.com/JAYIT/p/5200421.html