Skip to content

Instantly share code, notes, and snippets.

@oofnivek
Created January 11, 2024 12:46
Show Gist options
  • Save oofnivek/bbb6ab521a5837e5bf0f482af67c68d5 to your computer and use it in GitHub Desktop.
Save oofnivek/bbb6ab521a5837e5bf0f482af67c68d5 to your computer and use it in GitHub Desktop.
Appending string to file
package org.example;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import static java.util.UUID.randomUUID;
public class Main {
public static void main(String[] args) {
// check if file exists
Path path = Paths.get("append.txt");
if(Files.notExists(path)){
try {
Files.createFile(path);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// append content to file
String content = "";
try {
for(int i=0; i<5; i++){
content = String.format("%s\n",randomUUID().toString());
System.out.print(content);
Files.write(path, content.getBytes(), StandardOpenOption.APPEND);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment