Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

Why does .txt file in Java always become empty when I run the program?

I am trying to read in a .txt file which acts as a database from my Java program. I have written to the file before running the program via TextEdit and using Java FileWriter class but the program remains to show an empty array after running these lines of code. This is the only bit that is creating the problem and the remaining parts of my code (not shown here) run perfectly fine when I use an ArrayList as a temporary database. Can someone help me find out why is the .txt file always empty?

String filePathName = "User Data.txt";
File userFile = new File(filePathName);

if (userFile.createNewFile()) {
    System.out.println("Database has been successfully created");
    System.out.println();
}

Scanner fileReader = new Scanner(userFile);
FileWriter fileWriter = new FileWriter(userFile);
Scanner userInput = new Scanner(System.in);
ArrayList<User> userInfo = new ArrayList<>();
boolean actionValid = false;

StringBuilder fileInput = new StringBuilder();
while (fileReader.hasNext()) {
    fileInput.append(" ").append(fileReader.next());
}

String[] fileList = fileInput.toString().split(" ");

System.out.println(Arrays.toString(fileList));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Explanation

You have

Scanner fileReader = new Scanner(userFile);
FileWriter fileWriter = new FileWriter(userFile);

So your reader and writer are both tied to userFile. While this is already a bad idea to begin with (they will interfere with each other), in this particular case it also causes your problem.

The reason why is because new FileWriter(userFile) will truncate the file before it starts writing. Hence the file is also empty for your fileReader immediatly.


Solution

You can open a FileWriter in append-mode by adding true as second parameter (check the documentation) but as said, the bigger problem is that you are having a reader and writer tied to the same resource at the same time.

I do not see you using the fileWriter in your code snippet. Hence I am suggesting to first finish all your reading and creating the fileWriter later, when you actually need it, after you are fully done reading it.

In case you actually want to read and write at the same time, you should prepare your new file content in a List<String> first and delay the actual writing to the moment when you are fully done writing.


NIO

One last note, prefer using NIO for such file operations. It is much simpler to use and will also ensure that you do not keep the streams open longer than necessary.


Comments

This section looks odd to me:

StringBuilder fileInput = new StringBuilder();
while (fileReader.hasNext()) {
    fileInput.append(" ").append(fileReader.next());
}

String[] fileList = fileInput.toString().split(" ");

You are reading the file and preparing a StringBuilder just to split the result again. This is very wasteful. What you actually should use here is a List:

List<String> fileList = new ArrayList<>();
while (fileReader.hasNext()) {
    fileList.add(fileReader.next());
}

With NIO you could throw away your scanner and simplify to:

List<String> fileList = Files.lines(userFile.toPath())
    .collect(Collectors.toList());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...