InputStream输入类,首先需要读取的内容转化成输入流,再从它那里进行读取。
OutputStream输出类,首先需要与写入的目的地相关联,然后通过它进行写入。
输入:把要读取的内容输入到输入流,在从输入流进行读取,所以是read()。
输出:把要输出的东西通过输出流输出到目的地,所以是write()。
下面看两个例子
例1:向文件中写入字符串
import java.io.*;
public class OutputStream {
public static void main(String[] args) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
OutputStream out = new FileOutputStream(f);
String str = "Hello";
byte[]b = str.getBytes();
out.write(b);
out.close();
}
}
例2:从文件中读取
import java.io.*;
public class InputStream{
public static void main(String[] args) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
InputStream input = new FileInputStream(f);
byte [] b =new byte [(int)f.length()];
input.read(b);
input.close();
System.out.println("内容为:" + new String(b));
}
}