——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-
下图为Java IO流的总体图:
以下几点需要说明:
输入流的来源可以有多种,比如文件,键盘,网络等;输出流的目的地也可以有多种,比如文件,屏幕,网络等。
输入与输出的参照物为Java程序。输入是指将外部介质中的数据输入到Java程序;输出是指将数据从Java程序输出到外部介质。
大文件的读写方法:需要循环读取源文件,每次读取固定大小的字节(比如1k)放入目标文件。代码如下,以字节流为例:
import java.io.*;
public class Test {
public static void main(String [] args) {
try {
FileInputStream fis =
new FileInputStream("E:/from.txt");
FileOutputStream fos =
new FileOutputStream("E:/to.txt");
byte [] buffer = new byte[1024];
while(true) {
//循环读取源文件,每次读取1k大小的字节放入目标文件
int temp = fis.read(buffer, 0, buffer.length);
if(temp == -1) break;//读取到文件尾部
fos.write(buffer, 0, temp);
}
}
catch(Exception e) {
System.out.println(e);
}
finally {
try {
fis.close();
fos.close();
}
catch(Exception e) {
System.out.println(e);
}
}
}
}
Java的IO流设计使用了一种经典的设计模式,装饰者模式,将这些IO流分为两大类:
节点流:进行最基本的IO操作。比如FileReader,InputStreamReader
处理流:在最基本的IO操作基础上,增加了一些其它操作。比如BufferedReader,在FileReader的基础上,提供了一次读取一行的操作,readline(),例子代码:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class RecordTime {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(
new FileReader("/home/time.txt"));
String line = null;
String time = null;
ArrayList<Integer> timeList = new ArrayList<Integer>();
int totalTime = 0;
int minTime = 0;
int maxTime = 0;
line = br.readLine();
while (line != null) {
if(line.startsWith("time=")) {
time = line.substring(5);
timeList.add(Integer.parseInt(time));
}
line = br.readLine();
}
br.close();
for(int i = 0; i < timeList.size(); i++) {
System.out.println(timeList.get(i));
totalTime += timeList.get(i);
if(i == 0) {
minTime = timeList.get(i);
maxTime = timeList.get(i);
} else if (timeList.get(i) < minTime) {
minTime = timeList.get(i);
} else if (timeList.get(i) > maxTime) {
maxTime = timeList.get(i);
}
}
System.out.println("Avarage time is " + totalTime/timeList.size());
System.out.println("Min time is " + minTime);
System.out.println("Max time is " + maxTime);
BufferedWriter bw = new BufferedWriter(
new FileWriter("/home/time_record.txt"));
bw.write("Avarage time is " + totalTime/timeList.size());
bw.newLine();
bw.write("Min time is " + minTime);
bw.newLine();
bw.write("Max time is " + maxTime);
bw.newLine();
bw.flush();
bw.close();
timeList.clear();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}