java write to file line by line 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.write("Hello World".getBytes());

file.close();

Example 3: 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();