Java 字节流实现文件读写操作(InputStream-OutputStream)

本文介绍使用Java中的字节流(InputStream和OutputStream)进行文件读取和写入的基本方法。通过具体示例展示了如何创建FileInputStream和FileOutputStream对象,并使用它们来读取和写入文件内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java 字节流实现文件读写操作(InputStream-OutputStream)

备注:字节流比字符流底层,但是效率底下。

字符流地址:http://pengyan5945.iteye.com/blog/1092354

package com.frank.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * author:pengyan 
 * date:Jun 15, 2011 
 * file:InputOutputStreamTest.java
 */
public class InputOutputStreamTest{
	File f=new File("F:\\abc.txt");
	public static void main(String[] args) throws Exception{
		InputOutputStreamTest test=new InputOutputStreamTest();
		test.outputFile("Java字节流读写文件测试!");
		test.inputFile();
	}
	private void inputFile() throws IOException{
		//reate FileInputStream with file
		FileInputStream fis=new FileInputStream(f);
		//in order to receive the value of this stream read every time
		int temp=0;
		//the all content of this stream read 
		String str="";
		while((temp=fis.read())!=-1){
			//if not end,the total content add the value of the stream read this time
			str+=(char)temp;
		}
		//create a new String object with the correct encode 
		System.out.println("文件内容:"+new String(str.getBytes("ISO-8859-1")));
	}
	private void outputFile(String content) throws IOException {
		if (f.exists()==false) {
			f.createNewFile();//create file if not exist
		}
		//create FileOutputStream with file
		FileOutputStream fos=new FileOutputStream(f);
		//output file
		fos.write(content.getBytes());
		//flush this stream
		fos.flush();
		//close this stream
		fos.close();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值