文件输入流 和输出流

对文件输入和输出的操作

获取文件 java.io.File

File类在创建对象的时候(调用构造方法)必须指定文件路径名

写路径名时/必须是//而用\则只要\

File类只能查询文件的信息,但是不能对文件执行其他写入或读取操作

File类下的方法:

file.exists()判断该路径下的该文件是否存在,返回值为boolean

file.getAbsolutePath()获取该文件的绝对路径

file.isDirectory()判断是否是文件夹还是目录

file.mkdir()创建最后一级目录,返回创建目录是否成功

file.mkdirs()递归创建

file.isFile()返回是否是文件

file.length()返回文件大小,单位是字节

file.list()返回目录下所有的文件列表

file.getName()返回文件名

file.listFiles()获取到目录下的文件列表

 

 

IO流分类:输入流和输出流

输入流:字节输入流和字符输入流

字节输入流:FileInputStream

Byte[] b=new Byte[1024];

FileInputStream fis=new  FileInputStream(file);

Fis.skip(2);//字节偏移量

Int a=fis.read();//读到最后不能再读,返回附一

While(a!=-1){

a=fis.read(b);//将文件内容输入到b数组中

}

String str =new String(b);//字节字符转成字符串

 

字节输出流:FileOutputStream

FileOutputStream fos=new FileOutputStream(file,true);//true值为判断是否在原内容上追加内容而不是覆盖

 

字符输入流:FileReader

字符输出流:FileWriter

FileReader reader=new FileReader(file);

 

字节转字符

输入流:InputStreamReader

InputStreamReader reader=new InputStreamReadernew  FileInputStream(file);//

 

字符转字节

直接getbyze

 

如果需要按行读,必须要套用一个缓冲器BufferedReader

BufferedReader br=new BufferedReadernew InputStreamReadernew  FileInputStream(file)));

Br.readLine();

注意:流使用完需要关闭

当读取文件是文本文件建议用字符流,

 附:文件间复制内容:

public class IOFile {
 public static void main(String[] args) {
	File file=new File("E://文件.txt");
	File file2=new File("E://接受文件.txt");
	FileInputStream inputStream=null;
	
	FileOutputStream outputStream=null;
	try {
		inputStream=new FileInputStream(file);
		
		outputStream=new FileOutputStream(file2);
		byte[] buf = new byte[1024];
		int b=0;
		while((b= inputStream.read(buf))!=-1){
		
			outputStream.write(buf, 0, b);
			
		}
		
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally{
		
		try {
			outputStream.close();
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
}


字节流与字符流的区别在;

传输单位不同:字节流以字节为单位,字符流以两个字节的Unicode为单位

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值