Pacific-Design.com

    
Home Index

1. Java

2. Files

+ Read File

Java / Files /

Java - Read Write Append from/to File

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class ReadWrite {

    /*-----------------------------------------------------------------------------------------------*/
    private static void readFile(String filename) throws IOException {

        FileInputStream fis = new FileInputStream(filename);

        BufferedReader br = new BufferedReader(new InputStreamReader(fis));

        String line;

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        br.close();
    }
    /*-----------------------------------------------------------------------------------------------*/

    public static void write2File(String filename, String line, boolean append) {

        try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, append)))) {
            out.println(line);

        } catch (IOException e) {
            System.out.println(e);
        }
    }
    /*-----------------------------------------------------------------------------------------------*/
    public static void splitLine(String line) {

        String[] tokens = line.split("[,|]");
        
        for(String token : tokens) {
            System.out.println(token);
        }
    }
    /*-----------------------------------------------------------------------------------------------*/

    public static void main(String[] args) throws IOException {

        readFile("src/readwrite/data.txt");
        write2File("src/readwrite/data2.txt", "Hello World", false);
        splitLine("Kevin,Thomas|Duraj");
    }
    /*-----------------------------------------------------------------------------------------------*/
}