</pre><pre code_snippet_id="1696412" snippet_file_name="blog_20160525_2_8740433" name="code" class="java">
package IO;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import javax.xml.crypto.Data;
import org.junit.Test;
public class TestOtherStream {
@Test
public void TestData() {
DataInputStream dataInput = null;
try {
dataInput = new DataInputStream(new FileInputStream(new File("data.txt")));
// byte[] bs = new byte[20];
// int len;
// while ((len = dataInput.read(bs)) != -1) {
//
// System.out.println(new String(bs, 0, len));
// }
String string=dataInput.readUTF();
System.out.println(string);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (dataInput != null) {
try {
dataInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// 数据流:处理基本数据类型、String、字节数组的数据
// DataInputStream和DataOutputStream,分别套接在InputStream和OutputStream节点流上
// 没有reader和writer因为不是文本
@Test
public void Data() {
DataOutputStream dataOutputStream = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream("data.txt");
dataOutputStream = new DataOutputStream(fileOutputStream);
dataOutputStream.writeUTF("I love u but u dont know !");
dataOutputStream.writeBoolean(true);
dataOutputStream.writeLong(34153454);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// 打印流:字节流PrintStream字符流PrintWriter
@Test
public void printStreamWriter() {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File("print.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节'\n',时会刷新输出缓冲区)
PrintStream pStream = new PrintStream(fileOutputStream, true);
// 把标准输出流(控制台输出)改成文件输出
if (pStream != null) {
System.setOut(pStream);
}
for (int i = 0; i < 255; i++) {
System.out.print((char) i);// 输出ASCII字符
if (i % 50 == 0) {
System.out.println();// 每50个数据换行
}
}
pStream.close();
}
}