MENU

FileInput(Output)Stream

June 24, 2018 • Read: 226 • Java

FileInputStream

import java.io.*;
public class TestFileInputStream {
    public static void main(String[] args) {
        int b = 0;
        FileInputStream in = null;
        try {
            in = new FileInputStream("D:\\test.txt");
        }catch(FileNotFoundException e) {
            System.out.println("找不到指定文件");
            System.exit(-1);
        }
        try {
            long num = 0;
            while((b = in.read()) != -1){//判断是否读到结尾 
                System.out.print((char)b);
                num++;
            }
            in.close();
            System.out.println();
            System.out.println("共读取了" + num + "个字节");
        }catch(IOException e1) {
            System.out.println("文件读取错误");
            System.exit(-1);
        }
    }
}

程序第8行调用FileInputStream构造方法,参数为一个文件的路径,会抛出异常,所以必须要catch
image

其次,FileInputStream一个字节一个字节往外读,如果文件中有中文,中文是两个字节,读出来的中文就无法正常的显示,把FileInputStream改为FileReader即可解决这个问题

FileOutputStream

import java.io.*;
public class TestFileOutputStream {
    public static void main(String[] args) {
        int b = 0;
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream("D:/test.txt");
            out = new FileOutputStream("D:/test1.txt");
            while((b = in.read()) != -1) {
                out.write(b);
            }
            in.close();
            out.close();
        }catch(FileNotFoundException e2) {
            System.out.println("找不到指定文件");
            System.exit(-1);
        }catch(IOException e1) {
            System.out.println("文件复制错误");
            System.exit(-1);
        }
        System.out.println("文件已复制");
    }
}

第八行是将“管道”插在test.txt上准备读,第九行是将“另一根管道”插在test1.txt上准备写,如果准备要写入的文件不存在,FileOutputStream会自动创建

最后编辑于: October 19, 2018
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment