用IO流对文件进行操作

一、对文件进行读写操作


1.使用FileInputStream读取数据

	//从文件中读取数据
	public static void FileInputStream() throws IOException{
		FileInputStream in=new FileInputStream("E:\\test.txt");
		int tmp;
		String result="";
		while ((tmp=in.read())!=-1) {
			result+=(char)tmp;
		}
		System.out.println(result);
		
		in.close();
		

	}


2.把数据写入文件中


//使用FileOutputStream写入数据

	public static void FileOutputStream() throws IOException{
		//如果第二个参数为 true,则将字节写入文件末尾处
		java.io.FileOutputStream out=new java.io.FileOutputStream("E:\\test.txt",true);
		String str="how are you ?";
		byte[] b=str.getBytes();
		out.write(b);
		
		out.close();

	}



//使用PrintStream或者PrintWriter

	public static void B() throws FileNotFoundException{
		//创建文件输出流(向文件中写入数据)
//		FileOutputStream fos=new FileOutputStream(new File("E:"+File.separator+"test.txt"));
		//如果第二个参数为 true,则将字节写入文件末尾处(没有这个参数则根据路径新建文件夹,同上的另一种写法)
		FileOutputStream fos=new FileOutputStream("E:"+File.separator+"test.txt",true);
		//创建字节打印流
		PrintStream ps=new PrintStream(fos);
		ps.println("it's wonderful !");
		ps.println("it's beaultiful !");
		
		String name="刘星";
		int age=14;
		float score=990.356f;
		String sex="male";
		//格式化输出printf();
		ps.printf("姓名:%s;年龄:%s;成绩:%s;性别:%s",name,age,score,sex);
		ps.println();
		ps.close();

	}


二、对文件进行复制


public static void copy() throws IOException{
		FileInputStream in=new FileInputStream("E:\\test.txt");
		java.io.FileOutputStream out=new java.io.FileOutputStream("C:\\test11.txt");
		//先定义一个字节缓冲区,减少I/O次数,提高读写效率
		byte[] buffer=new byte[10240];
		int len;
		//FileOutputStream.write(byte[] b,int off,int len)
		//指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
		
		while ((len=in.read(buffer))!=-1) {
			out.write(buffer, 0, len);
		}
		
		/*while ((len=in.read())!=-1) {
			out.write((char)len);
		}*/
		in.close();
		out.close();
		 
	}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值