The BufferedWriter
does not write to file "segfil.txt":
public static String fileSeg(String name, int co) throws IOException {
String randomString = "";
File fil5 = new File("segfil.txt");
Random r;
System.out.println("Dude what??");
BufferedReader reader = new BufferedReader(new FileReader(name));
BufferedWriter bfwt = newBufferedWriter(newFileWriter(fil5.getName()));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
System.out.println(line);
System.out.println("++++++++");
bfwt.write(line);
while (line != null) {
lines.add(line);
line = reader.readLine();
}
// Choose a random one from the list
while (co > 0) {
r = new Random();
randomString = lines.get(r.nextInt(lines.size()));
System.out.println(randomString);
bfwt.write(randomString);
System.out.println(co);
co--;
}
return fil5.getName();
}
I have generated the random lines but cannot write to another file. The file remains blank as it is not written.
You should use try-with-resources to automatically close the files (and hence flush, in the case of the Writer):
try (BufferedReader reader = new BufferedReader(new FileReader(name));
BufferedWriter bfwt = newBufferedWriter(newFileWriter(fil5.getName()))) {
// Code using reader and bfwt.
}
Did you try to flush after writing?
bfwt.write(randomString);
bfwt.flush();
Or do you have any errors?
You don't close your resources/streams. You need to improve resource management from your code. Use try-with-resources statement :
List<String> lines = new ArrayList<>();
try (
FileReader fileReader = new FileReader("...");
BufferedReader bufferedReader = new BufferedReader(fileReader);
) {
String line;
while ( (line = bufferedReader.readLine()) != null) lines.add(line);
}
You can also rely on Path
and Stream
APIs:
List<String> lines = Files.lines(Paths.get("")).collect(Collectors.toList());
Same logic apply to write:
Random random = ThreadLocalRandom.current();
try (FileWriter fileWriter = new FileWriter("...")) {
for (int i = 0; i < co; i++) {
int lineNumber = random.nextInt(lines.size());
String line = lines.get(lineNumber);
fileWriter.write(line);
fileWriter.write('\n');
}
}
with Path
and Stream
APIs:
Files.write(
Paths.get("..."),
ThreadLocalRandom.current()
.ints(co, 0, lines.size())
.mapToObj(lineNumber -> lines.get(lineNumber))
.collect(Collectors.toList())
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.