filehandler

mail@pastecode.io avatar
unknown
java
a year ago
2.7 kB
7
Indexable
Never
package filehandling;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
 *
 * @author HP
 */
public class Filer {

    private String fileName = "chaman.txt";

    public Filer(String fileName) {
        this.fileName = fileName;
    }

    public String getFileName() {
        return fileName;
    }

    public File getFile() {
        File myFile = new File(fileName);
        if (myFile.exists()) {
            return myFile;
        } else {
            return null;
        }
    }

    public void createFile() {
        File myFile = new File(fileName);
        try {

            if (myFile.createNewFile()) {
                System.out.println("New File has been created.");
            } else {
                System.out.println("File already exists at  " + myFile.getAbsolutePath());
                System.out.println("Length of file is: " + myFile.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void writeInFile(String text) {
        FileWriter outputStream = null;
        try {
            outputStream = new FileWriter(fileName, true);
            outputStream.write(text + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void readFromFile() {
        Scanner sc;
        try {
            sc = new Scanner(new File(fileName));
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void copyAtoB(File a, File b) throws IOException {
        {
            FileInputStream in = new FileInputStream(a);
            FileOutputStream out = new FileOutputStream(b);
            try {
                int n;
                while ((n = in.read()) != -1) { // while in.read is not empty
                    out.write(n);
                }
            } finally {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }
            System.out.println("File Copied");
        }
    }
}