一、实践:将一个long型整数写到文件中,最开始使用DataOutputStream套接在FileOutputStream上,代码如下:
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestDataInputStream {
public static void main(String[] args) {
long n = 10000L;
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream("D:\\hehe.txt")); //对于FileOutputStream而言,hehe.txt若不存在,会自动创建
dos.writeLong(n);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dos != null) {
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
打开hehe.txt,发现为乱码。原因:DataOutputStream是用来写二进制数据的,用DataInputStream按写的顺序读进来才可看到原来的数据。
如果想使写入文件的数据可读,需要用到PrintWriter类,代码如下:
package com.lqh.test;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class TestDataInputStream {
public static void main(String[] args) {
long n = 10000L;
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileWriter("D:\\hehe.txt"));
pw.print(n);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(pw != null) {
pw.close();
pw = null;
}
}
}
}