java中读出txt文件内容并修改怎么写入原txt文件

java中读出txt文件内容并修改怎么写入原txt文件

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
 
public class App {
     
    /**
     * 保存 list 到指定文件
     * @param list
     * @param filePath
     * @throws IOException 
     * @throws FileNotFoundException 
     */
    static void save(List<String> list, String filePath) throws FileNotFoundException, IOException {
         
        try ( FileOutputStream outputStream = new FileOutputStream(filePath);
                OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream);
                BufferedWriter writer = new BufferedWriter(streamWriter)
                ) {
             
            for (String line : list) {
                writer.write(line + System.lineSeparator());
            }
        }
    }
     
    public static void main(String[] args) throws IOException {
 
        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        List<String> list3 = new ArrayList<>();
         
        File file = new File("d:/temp/0.txt");
         
        try ( FileInputStream stream = new FileInputStream(file);
                InputStreamReader streamReader = new InputStreamReader(stream);
                BufferedReader reader = new BufferedReader(streamReader) ) {
             
            String line = "";
             
            while((line = reader.readLine()) != null) {
                 
                // 去除开始的数字
                line = line.replaceFirst("\\d+", "");
                System.out.println(line);//这是读取到的文本内容
                if (line.contains("Organ")) {//如果文本内容中包含Organ就放到list1中(1.txt中)
                    // 包含 Organ 放入 list1
                    list1.add(line);
                } else if (line.contains("Location")) {
                    // 包含 Location 放入 list2
                    list2.add(line);
                } else if (line.contains("Person")) {
                    // 包含 Person 放入 list3
                    list3.add(line);
                }
            }
        }
         
        if (!list1.isEmpty()) {
            save(list1, "d:/temp/1.txt");
        }
         
        if (!list2.isEmpty()) {
            save(list2, "d:/temp/2.txt");
        }
         
        if (!list3.isEmpty()) {
            save(list3, "d:/temp/3.txt");
        }
    }
}

你可能感兴趣的:(后端,java)