how to write in a file java code example
Example 1: Java program to write to text file
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteIntoTextFile
{
public static void main(String[] args)
{
try
{
FileWriter fw = new FileWriter("B:\\demo.txt");
fw.write("Hello World");
fw.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
System.out.println("Successful");
}
}
Example 2: write file java
@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);
}