不论是InputStream或者是OutputStream都是抽象类,都需要一个实现它的子类
字符流是字节流的转化,通过jvm的encode来对字节流进行处理,进行字符集的转化,它们之间通过InputStreamReader和OutputStreamWrite来关联
InputStreamReader(InputStream in,String charset)和OutputStreamWriter (. .)可以不指定编码表,可以指定编码表
还有IO操作属于资源操作,使用完毕之后释放资源
在所有的硬盘上保存文件或进行传输的时候都是以字节的方法进行的,包括图片也是按字节完成,而字符是只有在内存中才会形成的,所以使用字节的操作是最多
一、字节输出流
public class OutputStreamText {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
OutputStream out=new FileOutputStream(f);//如果文件不存在会自动创建
String str="Hello World";
byte[] b=str.getBytes();
out.write(b);//因为是字节流,所以要转化成字节数组进行输出
out.close();
}
}
public class OutputStreamText2 {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
OutputStream out=new FileOutputStream(f);
//如果文件不存在会自动创建
//这样做的话会覆盖每一次写的内容,可以使用另一个构造方法 FileOutputStream(File f,boolean append),true表示会在末尾输出,而不会覆盖原有内容
String str="Hello World";
byte[] b=str.getBytes();
for(int i=0;i<b.length;i++){
out.write(b[i]);
}
out.close();
}
}
二丶字节输入流
public class InPutStreamTest {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
//File类中包含一些静态字段,separator含有一个separatorChar的字段,在windows中表示“\”,在unix中表现为"/",跨平台的时候最好使用
InputStream in=new FileInputStream(f);
byte[] b=new byte[1024];
int len=in.read(b);
in.close();
System.out.println(new String(b,0,len));
}
}
三丶字符输出流
public class WriterTest {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
Writer out=new FileWriter(f);
//同样的它也有另一个构造方法,boolean append 用来表示是否追加
String str="Hello World";
out.write(str);
out.close();
}
}
四丶字符输入流
public class ReaderTest {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
Reader input=new FileReader(f);
char[] c=new char[1024];
int len=input.read(c);
input.close();
System.out.println(new String(c,0,len));
}
}