Byte input stream and output stream of Java files

Byte input stream and output stream of java file

Input and output are relatively simple to understand from the program: the data that has been read from the hard disk to the memory is the input stream, and the data stored in the memory to the hard disk is the output stream.

Byte stream: Each operation is the input or output of the object unit. The most commonly used subclasses of FileInputStream and FileOutputStream are two byte streams. FileInputStream is the input stream and FileOutputStream is the output stream.
Byte input stream FileInputStream

Show some below 内联代码片.

// 给了一个[1024*1]的字节流
// byte[] arr = new byte[1024 * 1];
//这样可以加大流的输入,不用一个一个的字节输入加快输入速率
public static void main(String[] args) {
    
    
		// 创建输入流FileInputStream
		FileInputStream fileInput = null;
		try {
    
    
			// 创建文件地址
			fileInput = new FileInputStream("E:\\ccw.txt");
			// 给定一个字节大小
			// 每一次读取的时候就可以按照这个字节流输入
			byte[] arr = new byte[1024 * 1];// 给了一个[1024*1]的字节流
			int len = 0;
			while ((len = fileInput.read(arr)) != -1) {
    
    
				String str = new String(arr, 0, len);
				System.out.println(str);
			}
		} catch (Exception e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
    
    
			// 判断文件是否为空不为空关闭输入流
			if (fileInput != null) {
    
    
				try {
    
    
					fileInput.close();
				} catch (IOException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

Insert picture description here

Byte output stream FileOutputStream

Show some below 内联代码片.

public static void main(String[] args) {
		// 先创建一个文件在指定的磁盘下
		// 在E盘下创建一个名为csdn.txt的文本文档的标准文件夹
		String path = "E:" + File.separator + "csdn.txt";
		File file = new File(path);
		FileOutputStream fileOutput = null;
		try {
			// 判断文件是否创建成功
			boolean createNewFile = file.createNewFile();
			System.out.println(createNewFile);
			fileOutput = new FileOutputStream(file);
			// 将字节输出到指定的文件
			String str = "你身处年轻,辜负年轻,也快也将不再年轻!";
			// 将String型的字符串转换为字节数组
			byte[] arr = str.getBytes();
			// 利用write()方法实现输出流
			fileOutput.write(arr);
			// 输出后刷新文件
			fileOutput.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fileOutput != null) {
				try {
					fileOutput.flush();// 刷新文件
					fileOutput.close();// 关闭输出流
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

Insert picture description here

Remember to close the stream every time the input stream and output stream of bytes are completed (close() method)

Guess you like

Origin blog.csdn.net/fdbshsshg/article/details/113408694