写入文本

Writng to a txt

我有一个 txt 文件,我想扫描它并从中获取特定数据并将结果写入另一个 txt 文件。 它仅适用于我的系统打印行。 在我创建的新 txt 文件中写入对我不起作用,如果有人能告诉我我缺少什么,我将不胜感激!

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;

public class ReadingFile {

@SuppressWarnings({ "resource", "unused" })
public static void main(String[] args) throws Exception {
    // reading a current txt file
    File file = new File("C:/Users/Aboelmagd/Desktop/myfile1.txt");
    FileReader reader = new FileReader(file);
    BufferedReader br = new BufferedReader(reader);
    String reading;

    // Creating new txt to get the result
    File newFile = new File("C:/Users/Aboelmagd/Desktop/my.txt");
    FileWriter writer = new FileWriter(newFile);
    BufferedWriter bw = new BufferedWriter(writer);
    String writing;
    Scanner sc = new Scanner(reader);

    // Scanning myFile.txt and writing to my.txt
    while (sc.hasNext()) {
        writing = sc.next();
        // copying the full of myFile.txt to my.txt
        //bw.write(writing); 
        //bw.newLine();
        // If type is found, cet it and write to my.txt
        if (writing.contains("Type:")) {
            writing = writing.substring(0);
            // printing is working, yohooo :D
            System.out.println(writing);
            // writing to the my.txt is not working ?!!!
            bw.write(writing);
        }
    } 
  }
}

除非并且直到您调用 writer 对象的 close() 方法,否则内容不会被物理写入真实文件。始终在您的写作任务结束后关闭编写器。在您的情况下,请致电

 bw.close();

在你的 while 循环结束后。