JavaRush /Blog Java /Random-VI /Làm việc với các tệp bằng FileInputStream và FileOutputSt...
Artemka58_1
Mức độ

Làm việc với các tệp bằng FileInputStream và FileOutputStream

Xuất bản trong nhóm
Làm việc với các tệp có FileInputStreamFileOutputStream. Làm việc với file bằng FileInputStream và FileOutputStream - 1Tôi đang đọc cuốn sách của Schildt và bắt đầu làm việc với các tập tin. Ví dụ nói rằng bạn cần chạy chương trình từ dòng lệnh và nhập tên tệp. Nhưng tôi đang học ở IntelliJ. Làm cách nào để làm việc với các tệp bằng cách chỉ định đường dẫn đến chúng? Đây là một ví dụ:
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.");
        }
    }
}
Bình luận
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION