java读写文件以及一个文件内容写入另外一个文件的方法

java读写文件代码


  
  
  1. package readAndWriteFiles;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. public class Fangfa {
  6. public static void main(String[] args) throws Exception {
  7. readFile();
  8. writeFile();
  9. }
  10. //读入文件
  11. public static void readFile() throws Exception {
  12. File file = new File(“F:\\java-html项目\\项目文件\\day02\\test01.txt”);//读取文件路径
  13. FileInputStream fis = new FileInputStream(file);//建立一个输入流对象
  14. byte[] buf = new byte[1024];//每次读入文件数据量
  15. int len = -1;
  16. StringBuffer sbuf = new StringBuffer(“”);
  17. while ((len = (fis.read(buf))) != -1) {
  18. sbuf.append(new String(buf, 0, len));
  19. }
  20. System.out.println(sbuf.toString());
  21. fis.close();
  22. }
  23. //写入文件
  24. public static void writeFile() throws Exception {
  25. File file = new File(“F:\\java-html项目\\项目文件\\day02\\test02.txt”);//写入路径
  26. FileOutputStream fos = new FileOutputStream(file);
  27. fos.write(“Hello File”.getBytes());
  28. fos.close();//关闭文件
  29. }
  30. }

下面是将一个文件的内容写入到另外一个文件的代码

  
  
  1. public static void copyFile() throws Exception{
  2. File file1 = new File(“F:\\java-html项目\\项目文件\\day02\\test01.txt”);//读取文件路径
  3. FileInputStream fis = new FileInputStream(file1);//建立一个输入流对象
  4. File file2 = new File(“F:\\java-html项目\\项目文件\\day02\\test02.txt”);//写入路径
  5. FileOutputStream fos = new FileOutputStream(file2);
  6. byte[] buf = new byte[1024];//每次读入文件数据量
  7. int len = -1;
  8. StringBuffer sbuf = new StringBuffer(“”);
  9. while ((len = (fis.read(buf))) != -1) {
  10. sbuf.append(new String(buf, 0, len));//将 buf 数组参数的子数组的字符串表示形式追加到此序列
  11. //从0开始,遇到len(-1)结束
  12. }
  13. fos.write(buf);

  
  
  1.     fos.close();//关闭文件
  2. }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值