1.输入和输出:流代表任何有能力产出数据的数据源对象或者是有能力接收数据的接收端对象。read()方法用于读取单个字节或者字节数组。InputStream的作用是用来表示那些从不同数据源产生输入的类。OutputStream决定了输入要去往的目标。
OutputStream示例:
public static void main(String[] args) throws Exception {
File f = new File("b.txt");
OutputStream out = new FileOutputStream(f);
String str = "Hello";
byte[] b = str.getBytes();
out.write(b);
out.close();
}
InputStream示例:
public static void main(String[] args) throws Exception {
File f = new File("b.txt");
InputStream input = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
input.read(b);
input.close();
System.out.println(new String(b));
}
2.Reader和Writer:Reader与Writer类则是用来处理“字符流”的。使用write(String str)方法写数据,参数就是需要写到文件中的字符串。使用read()方法读取下一个字符,得到对应的ASCII或Unicode值,每次调用read()方法,都会尝试读取下一个新字符。
Writer示例:
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("d.txt");
fw.write("Hello World");
fw.close();
}
Reader示例:
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("d.txt");
int ch;
while ((ch = fr.read()) != -1) {
System.out.println(ch);
}
fr.close();
}
3.标准I/O:意义:可以很容易地把程序串联起来,一个程序的标准输出可以成为另一程序的标准输入。从标准输入中读取java提供了System.in、System.out和System.err;调用readLine()一次一行地读取输入。
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = br.readLine()) != null && s.length() != 0)
System.out.println(s);
}
4.新I/O:新IO采用内存映射文件的方式来处理输入输出。速度的提高来自于所使用的结构更接近于操作系统执行I/O的方式:通道和缓冲器,Channel(通道)和Buffer(缓冲)是新IO中的两个核心对象;Channel可以通过map方法可以直接将一块数据映射到内存中;Buffer相当一个容器,Channel中的所有对象或读取的数据,都必须首先放到Buffer中。
public static void main(String[] args) throws IOException {
FileInputStream f1 = new FileInputStream(new File("a.txt"));
FileOutputStream f2 = new FileOutputStream(new File("b.txt"));
FileChannel fc1 = f1.getChannel();
FileChannel fc2 = f2.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (fc1.read(byteBuffer) != -1) {
byteBuffer.flip();
fc2.write(byteBuffer);
byteBuffer.clear();
}
f1.close();
f2.close();
fc1.close();
fc2.close();
}

被折叠的 条评论
为什么被折叠?



