Chapter01 流与文件(一) 流

来源:互联网 发布:狩猎波尔卡 知乎 编辑:程序博客网 时间:2024/05/21 20:56

在Java API中,能够读入一个字节序列的对象成为输入流,能够写入一个字节序列的对象成为输出流。

字节流的祖宗是抽象类InputStream和OutputStream;特定处理字符的字符流的祖宗都是Reader和Writer。

InputStream的方法:read()方法遇到文件的结尾就会返回-1。


对文件的读写完成后,应该调用close()方法关闭流,释放比较少的操作系统资源。

整个字节流家族如下:


字符流如下:


字符、字节流各自实现的接口


当读入输入的时候,如果你想知道读入的值是否是你想要的,可以采用PushbackStream,需要一系列的中介流,包装如下:


字节流字符流的一些测试:

public class ZipStream {@Testpublic void testFile() throws IOException{//由于分隔符分不确定性改用从类中获取File file=new  File("src"+File.separator+"1.txt");FileOutputStream out=new FileOutputStream(file);out.write("HelloWorld".getBytes());out.close();}@Testpublic void testCharStream() throws FileNotFoundException{File file=new File("src"+File.separator+"employee.txt");//使用字符流PrintWriter writer=new PrintWriter(file);String name="张三";double salary=5423.23;writer.print(name);writer.print("\t");writer.print(salary);writer.close();}}

需要注意的点:


获取特定实现中那些字符集是可用的:

@Testpublic void testCharset(){//获取本地可利用的字符集Map<String, Charset> charSets=Charset.availableCharsets();for (Map.Entry<String, Charset> s: charSets.entrySet()) {System.out.println(s.getKey()+":"+s.getValue());}/* * 使用特定的字符集对java字符串进行编码,转化为字符序列 * 在本地方法中不一定能转化成功 *///该方法大小写不敏感Charset charset=Charset.forName("GBK");//得到GBK字符集的别名Set<String> sets=charset.aliases();for (String string : sets) {System.out.println(string);}//指定特定的编码形式String s=new String("中国".getBytes(),Charset.forName("UTF-8"));//ByteBuffer buffer=charset.encode(s);byte[] bs=buffer.array();//将上述生成的字节序列转化为字符串ByteBuffer byteBuffer=ByteBuffer.wrap(bs,0,bs.length);CharBuffer charBuffer=charset.decode(byteBuffer);System.out.println(charBuffer.toString());}

关于二进制数据的读写


DatainputStream实现了DataInput接口


@Test
public void testDataInput() throws IOException
{
File file=new File("src"+File.separator+"staff.dat");
DataOutputStream dataOutputStream=new DataOutputStream(new FileOutputStream(file));
dataOutputStream.writeChars("中国");
dataOutputStream.close();
DataInputStream in=new DataInputStream(new FileInputStream(file));
char c=in.readChar();
char d=in.readChar();
in.close();
System.out.println(c+""+d);
}