Java‎ > ‎

File IO

Writing to File:

import java.io.*;

class FileWrite {
    public static void main(String args[]) {
        try {

            FileWriter fstream = new FileWriter("out.txt");
//To append to the file use: FileWriter("filename", true)
            BufferedWriter out = new BufferedWriter(fstream);

            out.write("Hello Java");
            out.close();

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Read File:

import java.io.*;

class FileRead {
    public static void main(String args[]) {
        try {

            FileInputStream fstream = new FileInputStream("textfile.txt");


            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

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

            in.close();

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Create directory if it doesn't exists:

if(!(new File("C:\\temp")).exists())
new File("C:\\temp").mkdir();

Delete file:

File f = new File("file.txt");
boolean success = f.delete();

Copy file:
import org.apache.commons.io.FileUtils;

File source = new File("C:/myfile.txt");

File target = new File("D:/myfile_bak.txt");
try {
    FileUtils.copyFile(source, target);
} catch (IOException e) {
    APDispatcher.logger.error("failed to copy livelinux.conf to pxelinux.cfg");
}




Comments