现在的位置: 首页 > 综合 > 正文

大文件的读写方法

2017年12月05日 ⁄ 综合 ⁄ 共 1051字 ⁄ 字号 评论关闭
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.io.*;
class Test{
    public static void main(String
args[]){
        FileInputStream
fis =
null;
        FileOutputStream
fos =
null;
        try{
            fis
=
new FileInputStream("F:/Android/Java4Android/33/src/a.txt");
            //假设每次读取1024字节,
            byte []
b =
new byte[1024];
            fos
=
new FileOutputStream("F:/Android/Java4Android/33/src/b.txt");
            //使用循环多次读取大文件的数据
            while(true){
                int bLen
= fis.read(b,
0,b.length);
                //当程序已经读完了数据则返回-1
                if (bLen
== -
1){
                    break;
                }
                fos.write(b,0,bLen);
            }  
        }
        catch(Exception
e){
            System.out.println(e);
        }
        finally{
            try{
                //关闭IO流
                fis.close();
                fos.close();
            }
            catch(Exception
e){
                System.out.println(e);
            }
        }
    }
}

当文件的数据很大的时候,用字节流不可能一次性就读取完所有数据,可以分次循环读取再写入数据。字符流同理!

编程是门技能,熟能生巧,谢谢Mars老师!

抱歉!评论已关闭.