JAVA 基础之字节流

FileInputStream:当读取到文件的末尾时,当读到文件末尾时,read()会返回-1,根据这个返回值来判断是否已经读取到文件末尾。

当没有读到文件末尾时,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();
		}

	}

}

猜你喜欢

转载自blog.csdn.net/x1987200567/article/details/109351164
今日推荐