Created
January 11, 2024 12:46
-
-
Save oofnivek/bbb6ab521a5837e5bf0f482af67c68d5 to your computer and use it in GitHub Desktop.
Appending string to file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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