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());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…