写入txt

时间:2016-06-05 18:49:12

标签: java filewriter

我有一个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);
        }
    } 
  }
}

1 个答案:

答案 0 :(得分:0)

除非您调用writer对象的close()方法,否则内容将不会物理写入实际文件。总是,在你的写作任务结束后关闭作家。在您的情况下,请致电

start = os.times()
limit = 5  # seconds of user time
while True:
    # your code here
    check = os.times()
    if check.user - start.user > limit:
        break
在你的while循环关闭后