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
其次,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 会自动创建