IO内存操作

/**
 * 多个文件数据融合(a a + b b = a(b)a(b))
 * 1.创建一个把文件数据输入流和缓存数据输出流
 * 2.创建一个File数组,元素为内存操作类的参数
 * 3.创建一个字符串操作对象StringBuffer
 * 3.把File数组元素作为参数调用内存操作类,得到字符串后使用StringBuffer对字符串进行拼接
 * @author Administrator
 *
 */
public class TestDemo {
    public static void main(String[] args) throws Exception {
        File[] file = new File[] {
            new File("E:" + File.separator + "aaa" + File.separator + "a.txt"),
            new File("E:" + File.separator + "aaa" + File.separator + "b.txt")
        };
        String[] data = new String[2];    //定义一个字符串数组
        for(int x = 0;x < file.length;x++) {
            data[x] = readFile(file[x]);    //读取的数据放入到字符串数组内
        }
        StringBuffer buf = new StringBuffer();    //组合操作
        String[] contentA = data[0].split(" ");    //文件1字符串根据空格拆分返回数组类型
        String[] contentB = data[1].split(" ");    //文件2字符串根据空格拆分返回数组类型
        //把a、b文件的数保存在另一个文件中
        OutputStream output = new FileOutputStream(new File("E:" + File.separator + "aaa" + File.separator + "ab.txt"));
        for(int x = 0;x < contentA.length;x++) {
            String str = contentA[x] + "(" + contentB[x] + ")";
            buf.append(contentA[x]).append("(").append(contentB[x]).append(")");
            output.write(str.getBytes());    //在新文件中写入值
        }
        output.close();
        System.out.println(buf);    //从内存中读取a、b文件的数据
    }
    //File在内存中的操作
    public static String readFile(File file) throws IOException {
        if(file.exists()) {    //如果文件存在
            InputStream input = new FileInputStream(file);    //创建对文件的输入流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();    //读取缓存数据的输出流
            byte[] bt = new byte[1];    //每次缓存1个字节数组元素
            int temp = 0;
            while((temp = input.read(bt)) != -1) {    //每次从流末尾读取1个字节缓存到bt,返回读取个数1
                bos.write(bt, 0, temp);    //读取1个byte写入到输出流
            }
            input.close();    //关闭输入流
            bos.close();    //关闭输出流
            return new String(bos.toByteArray());    //返回输出流里被转换成byte[]类型的数据
        }
        return null;
        
    }

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值