//使用此方法不能读取大型文件
public class ReadFile {
public static void main(String[] args) {
byte bytes[] =new byte[1024];//定义缓冲区大小
int n=0;//得到实际读取的字节数
File file = new File("C:/Users/Chenxr/Desktop/卡密.txt");//定义读取的文件
try {
FileInputStream fis = new FileInputStream(file);
try {
while ((n=fis.read(bytes))!=-1) {
//下一个数据字节,如果到达流末尾,则返回 -1。
String string= new String(bytes, 0, n);
System.out.println(string);
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
运用此方法可以读取大型文件,原理:逐行读取缓冲区
public class ReadLargeFile {
// 此方法可以读取大文件
public static void main(String[] args) {
byte[] buf = new byte[1];// 存储数据的内部缓冲区数组
int n = 0;//
String string;
File file = new File("C:/Users/Chenxr/Desktop/卡密.txt");
try {
FileReader f1 = new FileReader(file);//读取文件流
BufferedReader br =new BufferedReader(f1);//读取到输入流
while ((string=br.readLine())!=null) {
System.out.println(string);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
//拷贝大型文件常用方法 bufferedInputStream
public class copyFile {
public static void main(String[] args) {
byte buf[] = new byte[10];// 定义缓冲区
int rd;
try {
FileInputStream f1 = new FileInputStream("D:/text.doc");//
FileOutputStream f2 = new FileOutputStream("D:/copy.doc");
BufferedInputStream bfi= new BufferedInputStream(f1);
BufferedOutputStream bfo = new BufferedOutputStream(f2);
while ((rd = bfi.read(buf, 0, 1)) != -1) /*将各字节读取到指定的 byte 数组中,若到结尾则返回-1*/
{
bfo.write(buf,0,1);//将内容写到f2文件中
}
bfi.close();
bfo.close();
f1.close();
f2.close();// 输入操作完成(复制操作)
} catch (IOException e) {
// TODO: handle excesption
}
}
}