CodeMonkey CodeMonkey -4 years ago 134
Java Question

File writing line by line

I'm writing a set of files, inside a directory. This is my code,

String directoryName = "logs";
File directory = new File(String.valueOf(directoryName));
if (!directory.exists()) {

System.out.println("Simulating logs....");
for (int i = 0; i < 1440; i++) {

long now = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1);

String fileName = now + ".txt";
Path filePath = Paths.get(directoryName, fileName);

LogGenerator generator = new LogGenerator(noOfServers);
Set<String> logs = generator.generateLog();
try {
Files.write(filePath, logs, Charset.forName("US-ASCII"));
} catch (IOException e) {


The issue is that, all the elements of the set logs are being appended after the first one and being written in the same line. This happens in this line,

Files.write(filePath, logs, Charset.forName("US-ASCII"));

I want to write each element of the set in a new line. How can i acheive this?

Answer Source

Here is what the javadoc says about the write method:

"Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset."

I would assume that the method does what the javadoc clearly says it does. Here are some alternative possible explanations:

  • The lines were concatenated by the generateLog() method.
  • There is a mismatch between Java's idea of what the platform line separator is (on the machine where the code is running) and the idea of the other app of what it is (on the machine where you are viewing the results).
  • You are viewing the output in a context where raw line separator characters are not rendered; e.g. an HTML document ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download