java:java中的字节流的练习,java字节流练习
分享于 点击 32201 次 点评:11
java:java中的字节流的练习,java字节流练习
package com.xudeyu.stream;import java.io.BufferedInputStream; 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.InputStream; import java.io.OutputStream; import java.io.PushbackInputStream; import java.nio.charset.Charset; import java.nio.file.FileSystem;
import javax.xml.stream.events.Characters;
public class StreamTest { public static void main(String[] args) throws IOException { // 一个文件 String fileName = "g:/javatest.dat";
MyStreamOut myOut = new MyStreamOut(fileName); myOut.fileOut(); myOut.dataOutChars("hello character!");
MyStreamIn myIn = new MyStreamIn(fileName); myIn.fileIn(); myIn.dataInBoolean(); myIn.pushbackStream(); } }
class MyStreamOut { // 所有方法输出到一个文本,便于测试 private String fileName;
// 所有方法公用操作字符数组; private byte[] b = { 'a', 'b', 'c', 'd', 'e' };
// 只可写入字节 private FileOutputStream fout;
// 可以写入数据 private DataOutputStream dout;
// 构造时设置默认文件名 public MyStreamOut(String fileName) { this.fileName = fileName; }
public void fileOut() throws IOException { fout = new FileOutputStream(new File(fileName), false); fout.write(b, 1, 3); fout.flush(); fout.close(); }
public void dataOutChars(String str) throws IOException { // 组合过滤器的使用,用fout流初始化dout流 fout = new FileOutputStream(new File(fileName), false);
// 初始化dout流 dout = new DataOutputStream(fout);
dout.writeChars(str); dout.flush(); dout.close(); } }
class MyStreamIn { // 默认文件名 private String fileName;
private FileInputStream fsin; private DataInputStream din; private PushbackInputStream pkin;
// 初始化时指定文件位置 public MyStreamIn(String fileName) { this.fileName = fileName; }
public void fileIn() throws IOException { fsin = new FileInputStream(fileName); byte b = (byte) fsin.read(); println(b); }
public void dataInBoolean() throws IOException { // 初始化file流 fsin = new FileInputStream(fileName);
// 用file流初始化 data流 din = new DataInputStream(fsin);
while (din.available() != 0) { println(din.readChar()); } }
// TODO this is error and method public void pushbackStream() throws IOException { pkin = new PushbackInputStream(new BufferedInputStream( new FileInputStream(fileName)));
while (pkin.available() != 0) { int b = pkin.read(); if (b != 'b') pkin.unread(b); }
}
public void peekAndBuffered() throws IOException { din = new DataInputStream(pkin = new PushbackInputStream( new BufferedInputStream(new FileInputStream(fileName)))); byte b = (byte) din.read(); if (b == 'h') { pkin.unread(b); }
}
private void println(Object obj) { System.out.print(obj); } }
相关文章
- 暂无相关文章
用户点评