JAVA basics byte stream

FileInputStream: When reading to the end of the file, read() will return -1. Use this return value to determine whether the end of the file has been read.

When the end of the file is not reached, read() returns the number of bytes actually read.

package com.filestream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class fileInputstreamDemo {

	public static void main(String[] args) {
		int fileLen = 0;
		
		FileInputStream fis;
		try {
			 
			fis = new FileInputStream("c:\\filetest\\file\\speech.txt");
			/*
			 * 读取方法1
			int temp = 0;
			while ((temp = fis.read()) != -1) {
				System.out.print((char)temp);
				fileLen++;
			}
                        fis.close();
			*/
			
			//读取方法2:
			byte []temp = new byte[26];
			fis.read(temp);
			System.out.println(new String(temp));
			fileLen = temp.length;
                        fis.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		System.out.println("file lenth : " + fileLen);
			
		
	}

}

FileOutputStream and BufferedOutputStream:

package com.filestream;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class bufferstreamDemo {

	public static void main(String[] args) {
		try {
			FileOutputStream fos = new FileOutputStream("c:\\filetest\\file\\one.txt");
			FileOutputStream fos2 = new FileOutputStream("c:\\filetest\\file\\two.txt");
			BufferedOutputStream bos = new BufferedOutputStream(fos2);
			long oneStarttime = System.currentTimeMillis();
			int temp1 = 0;
			while(temp1<100000) {
				fos.write('a');
				temp1++;
//				System.out.println("正在写one.txt: "+ temp1);
			}
			long oneEndTime = System.currentTimeMillis();
			System.out.println("one.txt不使用缓存流来写,用时为: " + (oneEndTime - oneStarttime));
			
			int temp2 = 0; 
			long oneStarttime2 = System.currentTimeMillis();
			while(temp2<100000) {
				bos.write('a');
				temp2++;
//				System.out.println("正在写two.txt: "+ temp2);
//				bos.flush();
			}
			long oneEndTime2 = System.currentTimeMillis();
			System.out.println("two.txt使用缓存流来写,用时为: " + (oneEndTime2 - oneStarttime2));
			
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

Guess you like

Origin blog.csdn.net/x1987200567/article/details/109351164