|--需求说明
实际操作过程中,从D盘根目录下的ak.txt读取文件写入D盘根目录下的hello.txt文件内
|--实现思路
写两个方法,一个用于读取目标文件,一个用于写入目标文件--详情见代码注释
|--代码内容
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 package com.io; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 8 /** 9 * @auther::9527 10 * @Description: 尝试 11 * @program: shi_yong 12 * @create: 2019-07-31 17:11 13 */ 14 public class Tyy { 15 public static void main(String[] args) { 16 //实例化对象 17 Tyy tyy = new Tyy(); 18 //用一个byte[]接受数据 19 byte[] bytes=tyy.read("d:/ak.txt"); 20 //将接受到的数据传入写入方法 21 tyy.write("d:/hello.txt",bytes); 22 23 } 24 25 //读取方法,设定传参是文件的String路径,返回一个byte[]数组 26 public byte[] read(String str) { 27 byte[] bytes = new byte[0]; 28 FileInputStream fis = null; 29 try { 30 fis = new FileInputStream(str); 31 int read; 32 bytes = new byte[1024000]; 33 System.out.println("内容读取中..........."); 34 while ((read = fis.read(bytes)) != -1) { 35 for (int i = 0; i < read; i++) { 36 System.out.print((char) bytes[i]); 37 } 38 System.out.println("\n内容读取完毕"); 39 } 40 return bytes; 41 } catch (FileNotFoundException e) { 42 e.printStackTrace(); 43 } catch (IOException e) { 44 e.printStackTrace(); 45 } finally { 46 try { 47 fis.close(); 48 } catch (IOException e) { 49 e.printStackTrace(); 50 } 51 } 52 return bytes; 53 } 54 55 //写入方法,需要两个参数,一是写入路径,一是写入内容 56 public void write(String string,byte[] bytes) { 57 System.out.println("文件写入中-----"); 58 FileOutputStream fos = null; 59 60 try { 61 fos = new FileOutputStream(string); 62 try { 63 fos.write(bytes); 64 } catch (IOException e) { 65 e.printStackTrace(); 66 } 67 System.out.println("文件写入完毕"); 68 69 } catch (FileNotFoundException e) { 70 e.printStackTrace(); 71 }finally { 72 try { 73 fos.close(); 74 } catch (IOException e) { 75 e.printStackTrace(); 76 } 77 } 78 } 79 }
|--运行结果