JAVA文件字节输入输出流

  • 输入流
    FileInputStream类创建指向文件的输入流;
FileInputStream(String name);
FileInputStream(File file);

以上参数name和file指定的文件称为输入流的源。

  1. 建立一个文件输入流:
try{
	FileInputStream in=new FileInputStream("hello.txt");
					//创建指向文件hello.txt的输入流
}
catch(IOException e){
	System.out.println(file read error:"+e);
}

  1. 用输入流读取字节
int read();//从源中读取《《单个》》字节的数据。未读出字节返回-1。
int read(byte b[]);//从源中读取b.length个字节暂存到字节数组b中。
int read(byte b[],int off,int len);//

String s=new String(a,o,n) :数组a从下标0开始前进n个下标的那一段数组变成字符串s;
3.使用文件字节流读取文件

import java.io.*;
public class Test1{
	public static void main(String args[]) throws IOException{
		int n=0;
		byte[] b=new byte[100];
		File file=new File("路径","123.txt");
		try {
			FileInputStream in=new FileInputStream(file);
			while((n=in.read(b,0,100))!=-1) {
				String s=new String(b,0,n);
				System.out.println(s);
			}
			in.close();//关闭流
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
  • 输出流
    FileOutputStream类创建指向文件的输出流;
FileOutoutStream(String name);
FileOutputStream(File file);

FileOutoutStream(String name,boolean append);
append 为true输出流不会刷新指向的文件。

创建一个输出流

try{
	FileOutputStream out=new FileOutputStream("123.txt");
}
catch(IOException e){
	System.out.println(e);
}
  • 使用输出流输出字节
void write(int n)//输出流调用该方法向目的地写入单个字节
void write(byte b[])写入一个字节数组
void write(byte b[],int off,int len)
void close()//关闭输入流

向一个文件写入”今天星期六"

import java.io.*;
public class Test1{
	public static void main(String args[]) throws IOException {
		byte b[]="今天星期六".getBytes();
		byte a[]="nowday is sunday".getBytes();
		File file=new File("路径","123.txt");
		if(!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream out=new FileOutputStream(file,true);
		out.write(a);
		out.close();
		
	}
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值