import java.io.FileWriter;
import java.io.IOException;
...
//write to file
try{
FileOutputStream writeData = new FileOutputStream("peopledata.ser");
ObjectOutputStream writeStream = new ObjectOutputStream(writeData);
writeStream.writeObject(people);
writeStream.flush();
writeStream.close();
}catch (IOException e) {
e.printStackTrace();
}
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
// Java Program to Write Into a File
// using writeString() Method
// Importing required classes
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
throws IOException
{
// Assigning the content of the file
String text
= "Welcome to geekforgeeks
Happy Learning!";
// Defining the file name of the file
Path fileName = Path.of(
"/Users/mayanksolanki/Desktop/demo.docx");
// Writing into the file
Files.writeString(fileName, text);
// Reading the content of the file
String file_content = Files.readString(fileName);
// Printing the content inside the file
System.out.println(file_content);
}
}
public void whenWriteStringUsingBufferedWritter_thenCorrect()
throws IOException {
String str = "Hello";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();
}
@Test
public void givenUsingJava7_whenWritingToFile_thenCorrect()
throws IOException {
String str = "Hello";
Path path = Paths.get(fileName);
byte[] strToBytes = str.getBytes();
Files.write(path, strToBytes);
String read = Files.readAllLines(path).get(0);
assertEquals(str, read);
}