首页 > 编程开发 > Java    日期:2020-11-25 / 来自互联网 / 浏览

字节(Byte)是进行io操作的基本数据单位,在程序进行字节数据输出时可以使用OutputStream类完成

此类定义如下:

public abstract class OutputStream
extends Object
implements Cloneable Flushable{}

在OutputStream类中实现了两个父接口 Closeable Flushable

这两个接口的定义分别如下

public interface Cloneable
extends AutoCloseable{
	public void close() throws IOException;
}
public interface Flushable{
	public void flush() throws IOException;
}

OutputStream定义了公共的字节输出操作,由于其定义为一个抽象类,所以需要依靠子类进行对象实例化,如果需要通过程序向文件内容进行输出 可以使用FileOutputStream子类

字符流的读写功能

	/**
	 * 字符流写功能
	 * @throws IOException 
	 */
	public static void demo4() throws IOException {
	Writer writer = new FileWriter("J:/demo2.txt",true);
	writer.write(123);
	writer.write("一二三");
	writer.write(879);
	writer.flush();
	writer.close();
	}
	
	/**
	 * 字符流读功能
	 * @throws IOException 
	 */
	
	public static void demo5() throws IOException {
		Reader reader = new FileReader("J:/demo2.txt");
		System.out.println((char)reader.read());
		System.out.println((char)reader.read());
		
		int a = 0;
		while((a=reader.read()) != -1) {
			System.out.println((char)reader.read());
		}
		
		reader.close();
	}	

创建文件并写入内容

/**
	 * 创建文件并写入内容
	 * 
	 * @throws IOException
	 */
	public static void demo1() throws IOException {
		File file = new File("J:/demo.txt"); // 创建这个文件
		OutputStream os = new FileOutputStream(file, true); // 创建流对象 最后加个true参数代表是续写不是重写,不写true的话下一次运行这个方法就是清空内容并且重写
		os.write(10);// 添加内容
		os.write(302);// 添加内容
		os.write(11);// 添加内容
		os.write("hello world".getBytes()); // 上面是添加数字类型, 这一行代表添加字符
		os.close(); // 关闭流
	}

两类操作流最大的区别就是在于字符流使用到了缓冲区(这样更适合进行中文数据的操作,)而字节流是字节进行数据处理操作。

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章