Java 文件读取和写入练习

|--需求说明

实际操作过程中,从D盘根目录下的ak.txt读取文件写入D盘根目录下的hello.txt文件内

 

|--实现思路

写两个方法,一个用于读取目标文件,一个用于写入目标文件--详情见代码注释

 

|--代码内容

 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 }
文件读取和写入练习

  

|--运行结果

 

 

转载于:https://www.cnblogs.com/twuxian/p/11278692.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值