java file io 复制文件

1.功能:复制test.txt文件的内容到新文件testout.txt

test.txt的内容:

hello
world

 

2.程序源码:

import java.io.*;
public class TestFileio {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
   File infile = new File("D:/fileio","test.txt");
   InputStream in = new FileInputStream(infile);
   
   File outfile = new File("D:/fileio","testout.txt");
   OutputStream out = new FileOutputStream(outfile);
   int len;
   byte[] buffer = new byte[1024];
   while( (len = in.read(buffer)) > 0 ){
    out.write(buffer,0,len);
   }
   in.close();
   out.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }

}

3.注意点:

a) 目录要写成D:/fileio,不能用D:\fileio

b) 要使用out.write(buffer,0,len),不能用out.write(buffer)

1) write(byte[] b)  

        将 b.length 个字节从指定的字节数组写入此输出流。
2) write(byte[] b, int off, int len)

        将指定字节数组中从偏移量 off 开始的 len 个字节写入此输出流。

如果写成b.write(buffer),那么文件的大小就是1024字节,world后面都是空格,

因为buffer是byte[1024],b.length等于1024。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值