1.关于不覆盖可以做到
一种笨方法:先读取文件内容,写在BufferWriter中,在写在BufferWriter追加你要写的东西- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.io.StringReader;
- public class WriterFile {
- /**
- * @param args
- * @throws IOException
- * @throws FileNotFoundException
- */
- public static void main(String[] args) throws FileNotFoundException, IOException {
- // TODO Auto-generated method stub
- //像D盘里面的abc.txt文件写内容 路径:d://abc.txt
- //writer("d://abc.txt", "12334");
- test4("aaaabbbbcccc", "d://abc.txt");
- }
-
- private static void test4(String str, String filePath) throws FileNotFoundException, IOException {
- // 将一段字符串写入文件末尾
- BufferedReader br = new BufferedReader(new FileReader(filePath)); // FileReader类可以开发文件
- String data = new String();
- String s;
- s = br.readLine();
- while (s != null) {
- // System.out.println(1);
- data = data + s + "\r\n";
- s = br.readLine();
- }
- br.close();
-
-
- //写,继续写
- System.out.println(data);
- br = new BufferedReader(new StringReader(data));
- PrintWriter fw = new PrintWriter(new File(filePath));
-
-
- // String strs = null;
- while((s = br.readLine()) != null) {
- fw.print(s);
- fw.print("\r\n");
- }
- //给指定的文件加一行数据
- fw.print(str);
- br.close();
- fw.close();
- System.out.println("写入成功!");
-
- }
- }
复制代码 2.修改或者删除a.text中某一行, 你要知道是哪一行对吧,假如修改第三行,或者删除第三行。- private static void test5(int i, String filePath, String str) throws FileNotFoundException, IOException {
- // 将一段字符串写入文件末尾
- BufferedReader br = new BufferedReader(new FileReader(filePath)); // FileReader类可以开发文件
- String data = new String();
- String s;
- int sign = 0; //测试独到第几行
-
- while ((s=br.readLine()) != null) {
- sign++;
- //这里就是要修改或者删除的代码
- if(sign != i) {
- data = data + s + "\r\n";
- }
- else {
- if(str != null)
- data = data + str + "\r\n";
- }
- }
- br.close();
-
- System.out.println(data);
- //写,继续写
- System.out.println(data);
- br = new BufferedReader(new StringReader(data));
- PrintWriter fw = new PrintWriter(new File(filePath));
-
- while((s = br.readLine()) != null) {
- fw.print(s);
- fw.print("\r\n");
- }
-
- br.close();
- fw.close();
- System.out.println("修改或者删除成功!");
复制代码 思路差不多,删除则传递为null |