Home  >  Article  >  Java  >  What is the difference between byte stream and character stream in java

What is the difference between byte stream and character stream in java

王林
王林forward
2020-11-25 15:46:472594browse

What is the difference between byte stream and character stream in java

##The difference analysis is as follows:

(Learning video sharing:

java Teaching Video)

Byte (Byte) is the basic data unit for io operations. When the program outputs byte data, you can use the OutputStream class to complete

Such definitions As follows:

public abstract class OutputStream
extends Object
implements Cloneable Flushable{}
In the OutputStream class, two parent interfaces Closeable Flushable are implemented

The definitions of these two interfaces are as follows

public interface Cloneable
extends AutoCloseable{
	public void close() throws IOException;
}
public interface Flushable{
	public void flush() throws IOException;
}
OutputStream defines a common byte output Operation, since it is defined as an abstract class, you need to rely on subclasses for object instantiation. If you need to output the file content through a program, you can use the FileOutputStream subclass

Reading and writing functions of character streams

	/**
	 * 字符流写功能
	 * @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();
	}	
Create files and write content

/**
	 * 创建文件并写入内容
	 * 
	 * @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(); // 关闭流
	}
The biggest difference between the two types of operation streams is that the character stream uses a buffer (this is more suitable for Chinese data operations), while the byte stream uses bytes. Data processing operations.

Related recommendations:

java introductory tutorial

The above is the detailed content of What is the difference between byte stream and character stream in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete
Previous article:What file is jar?Next article:What file is jar?