JavaRush /Java Blog /Random EN /Working with files using FileInputStream and FileOutputSt...
Artemka58_1
Level 21

Working with files using FileInputStream and FileOutputStream

Published in the Random EN group
Working with files with FileInputStreamand FileOutputStream. Working with files using FileInputStream and FileOutputStream - 1I’m reading Schildt’s book and got to the point of working with files. The example says that you need to run the program from the command line and enter file names. But I'm learning in IntelliJ. How to work with files by specifying the path to them? Here's an example:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile {
    public static void main(String[] args) {
        int i;

        FileInputStream fin;
        FileOutputStream fout;

        if (args.length != 2) {
            System.out.println("Usage: CopyFile From To.");
            return;
        }

        try {
            fin = new FileInputStream(args[0]);
        } catch (FileNotFoundException exc) {
            System.out.println("Input file not found.");
            return;
        }

        try {
            fout = new FileOutputStream(args[1]);
        } catch (FileNotFoundException exc) {
            System.out.println("Error opening output file.");
            try {
                fin.close();
            } catch (IOException exc2) {
                System.out.println("Error closing input file.");
            }
            return;
        }

        try {
            do {
                i = fin.read();
                if (i != -1) fout.write(i);
            } while (i != -1);
        } catch (IOException exc) {
            System.out.println("Fi;e error.");
        }

        try {
            fin.close();
        } catch (IOException exc) {
            System.out.println("Error closing input file.");
        }

        try {
            fout.close();
        } catch (IOException exc) {
            System.out.println("Error closing output file.");
        }
    }
}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION