import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.charset.StandardCharsets; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; public class Example { public static void main(String[] args) { Path filePath = Paths.get("newfile.txt"); try (OutputStream outputStream = Files.newOutputStream(filePath)) { byte[] data = "This is sample text.".getBytes(StandardCharsets.UTF_8); outputStream.write(data); } catch (IOException e) { System.err.println(e.getMessage()); } } }
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.charset.StandardCharsets; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; public class Example { public static void main(String[] args) { Path filePath = Paths.get("existingfile.txt"); try (OutputStream outputStream = Files.newOutputStream(filePath)) { byte[] data = "This is some new text.".getBytes(StandardCharsets.UTF_8); outputStream.write(data); } catch (IOException e) { System.err.println(e.getMessage()); } } }In this example, we assume that the file "existingfile.txt" already exists. We create a new output stream to overwrite the contents of this file using the Files.newOutputStream() method. We write some new text to this file using the write() method of the output stream. Java package: java.nio.file