当前位置: 代码迷 >> 综合 >> DataInputStream 与 DataOutputStream
  详细解决方案

DataInputStream 与 DataOutputStream

热度:84   发布时间:2023-12-14 01:41:15.0
/** 文件内容是:* 1234* 4567* * 读取后打印:* 825373492* 218772533* * */@Testpublic void InDemo() throws IOException{DataInputStream in = new DataInputStream(new FileInputStream("E:/test/1.txt"));while(in.available()>0){int d  = in.readInt();System.out.println(d);}in.close();}

在TXT中输入1234 4567,使用DataInputStream 读取然后再控制台打印的是825.。。。

然后使用UE打开如下图


31是1的ASCII码,0D 0A是回车换行,都是些十六进制的数,将他们转换为十进制,正好是打印的内容。


2.

	@Testpublic void OutDemo() throws IOException{DataOutputStream out = new DataOutputStream(new FileOutputStream("E:/test/2.txt"));for (int i = 1; i <= 20; i++) {out.write(i);}out.close();}
这个也是一样的道理,将数字写出到文件,使用记事本打开看到一堆乱码,其实记事本是利用这些字符到编码表中找到对应的字符进行显示的。


3.

	@Testpublic void testEnd() {DataInputStream in = null;try {in = new DataInputStream(new FileInputStream("E:/test/1.txt"));while (true) {short read = in.readShort();System.out.println(read);}} catch (FileNotFoundException e) {System.err.println("文件找不到!");// e.printStackTrace();} catch (IOException e) {System.out.println("Over!");// e.printStackTrace();} finally {try {if (in != null) {in.close();}} catch (IOException e) {e.printStackTrace();}}}
结束文件的读取除了测试1的available 之外,还可以使用捕获异常控制输入结束。

EOF就是end of file exception