how to write line by line to a file in java code example

Example 1: 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);
}

Example 2: how to write between lines in a file in java

RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw");

file.seek(200);

long pointer = file.getFilePointer();

file.close();

Tags:

Java Example