Java I/O, Files

To Do How to do
Write to a file
Write with FileWriter
OutputStream -> FileWriter

import java.io.FileWriter; 
import java.io.IOException; 

try {
	FileWriter myWriter = new FileWriter("D:FileHandlingNewFilef1.txt");
	myWriter.write("Hello world"); 
	myWriter.close(); 
	System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
	System.out.println("An error occurred.");
	e.printStackTrace();
}
Write with OutputStreams
String data = "This is a line of text inside the file.";
try {
      FileOutputStream file = new FileOutputStream("output.txt");
      OutputStreamWriter output = new OutputStreamWriter(file, optional Charset cs);
      output.write(data); // data.getBytes() ??
      output.close();
}
catch (Exception e) {
     e.getStackTrace();
}
Write With DataOutputStream
  throws IOException {
    String value = "Hello";
    FileOutputStream fos = new FileOutputStream("output.txt");
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
    outStream.writeUTF(value);
    outStream.close();
}	
Write with BufferedWriter
throws IOException {
    String str = "Hello";
    BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
    writer.write(str);
    
    writer.close();
}
APPEND string with BufferedWriter
  throws IOException {
    String str = "World";
    BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt", true));
    writer.append(' ');
    writer.append(str);
    
    writer.close();
}
Write with PrintWriter
  throws IOException {
    FileWriter fileWriter = new FileWriter("output.txt");
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print("Some String");
    printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
    printWriter.close();
}
Write With RandomAccessFile
private void writeToPosition(String filename, int data, long position) 
  throws IOException {
    RandomAccessFile writer = new RandomAccessFile("output.txt", "rw");
    writer.seek(position);
    writer.writeInt(data);
    writer.close();
}
Write With FileChannel
If we are dealing with large files, FileChannel can be faster than standard IO.
part of Java NIO
FileChannel operations are blocking and do not have a non-blocking mode. tutorial
  throws IOException {
    RandomAccessFile stream = new RandomAccessFile("output.txt", "rw");
	// can be created with FileOutputStream stream = new FileOutputStream("output.txt");

    FileChannel channel = stream.getChannel();
    String value = "Hello";
    byte[] strBytes = value.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
    buffer.put(strBytes);
    buffer.flip();
    channel.write(buffer);
    stream.close();
    channel.close();
}	
Write with writeString
java.nio.file.Files
Path utfFile = Files.createTempFile("some", ".txt");
Files.writeString(utfFile, "this is my string ää öö üü"); // UTF 8
// more options

Path anotherUtf8File = Files.createTempFile("some", ".txt");
Files.writeString(anotherUtf8File, "this is my string ää öö üü", StandardCharsets.UTF_8,
        StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
By default, it will write a UTF-8 file. the file will automatically be created (and truncated if it already exists). These options could be overridden.
Read from a file
Read with FileReader
FileReader sourceStream = null;
try {
	sourceStream = new FileReader("test.txt");
	int temp;
	while ((temp = sourceStream.read()) != -1)
		System.out.println((char)temp);
}
finally {
	if (sourceStream != null) sourceStream.close();
}
Read with BufferedReader
		BufferedReader reader;

		try {
			reader = new BufferedReader(new FileReader("sample.txt"));
			String line = reader.readLine();

			while (line != null) {
				System.out.println(line);
				// read next line
				line = reader.readLine();
			}

			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
Read with Files
NIO
    Path path = Paths.get("src/test/resources/fileTest.txt");
    String read = Files.readAllLines(path).get(0);
    Path path = Paths.get("src/test/resources/fileTest.txt");

    BufferedReader reader = Files.newBufferedReader(path);
    String line = reader.readLine();

Reading with Files.lines()
Path path = Paths.get("src/test/resources/fileTest.txt");

    Stream lines = Files.lines(path);
    String data = lines.collect(Collectors.joining("\n"));
    lines.close();

Reading with Scanner
    Scanner scanner = new Scanner(new File("output.txt"));
    scanner.useDelimiter(" ");

    assertTrue(scanner.hasNext());
    assertEquals("Hello,", scanner.next());
    assertEquals("world!", scanner.next());

    scanner.close();
Reading with DataInputStream
    DataInputStream reader = new DataInputStream(new FileInputStream("output.txt"));
    int nBytesToRead = reader.available();
    if(nBytesToRead > 0) {
        byte[] bytes = new byte[nBytesToRead];
        reader.read(bytes);
        result = new String(bytes);
    }
Reading with Channel
	RandomAccessFile reader = new RandomAccessFile("output.txt", "r");
    FileChannel channel = reader.getChannel();

    int bufferSize = 1024;
    if (bufferSize > channel.size()) {
        bufferSize = (int) channel.size();
    }
    ByteBuffer buff = ByteBuffer.allocate(bufferSize);
    channel.read(buff);
    buff.flip();
    
    System.out.println( new String(buff.array()));
    channel.close();
    reader.close();

Functional interfaces

Functional Interfaces are an interface with only one abstract method (Single Abstract Method (SAM)).
functional -> wraps a function as an interface.