java读写文件


一、IO流读写

 OutputStreamWriter outputStreamWriter=null;
 InputStreamReader inputStreamReader=null;
 try {
     File file = new File("a.txt");
     outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file),Charset.forName("UTF-8"));
     long start = System.currentTimeMillis();
     for(int i=0;i<3500000;i++){
         outputStreamWriter.write("天");
     }
     outputStreamWriter.flush();
     long end = System.currentTimeMillis();
     System.out.println("写入完成,共"+file.length()+"byte,用时"+(end-start)+"毫秒");

     inputStreamReader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
     int len;
     char[]chars=new char[1024*1024*20];//20M
     long start1 = System.currentTimeMillis();
     while ((len=inputStreamReader.read(chars))!=-1){
         //System.out.println(new String(chars).trim());
     }
     System.out.println(len);
     long end1 = System.currentTimeMillis();
     System.out.println("读取完成,共"+file.length()+"byte,用时"+(end1-start1)+"毫秒");
 } catch (FileNotFoundException e) {
     e.printStackTrace();
 } catch (IOException e) {
     e.printStackTrace();
 }finally {
     try {
         inputStreamReader.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
     try {
         outputStreamWriter.flush();
         outputStreamWriter.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
 }

二、FileChannel读写

FileChannel fileChannel=null;
try {
    fileChannel = new FileOutputStream(new File("a.txt")).getChannel();
    long start = System.currentTimeMillis();
    for(int i=0;i<3500000;i++){
        fileChannel.write(ByteBuffer.wrap("天".getBytes(StandardCharsets.UTF_8)));
    }
    long end = System.currentTimeMillis();
    System.out.println("写入完成,共"+fileChannel.size()+"byte,用时"+(end-start)+"毫秒");
    fileChannel= new FileInputStream(new File("a.txt")).getChannel();
    ByteBuffer byteBuffer = ByteBuffer.allocate((int) (fileChannel.size()));
    long start1 = System.currentTimeMillis();
    while (fileChannel.read(byteBuffer)!=0){
        System.out.println(new String(byteBuffer.array()).length());
    }
    long end1 = System.currentTimeMillis();
    System.out.println("读取完成,共"+fileChannel.size()+"byte,用时"+(end1-start1)+"毫秒");
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}finally {
    try {
        fileChannel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

三、行读文件

BufferedReader bufferedReader = null;
try {
    bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"),Charset.forName("UTF-8")));
    String content;
    while ((content=bufferedReader.readLine())!=null){
        System.out.println(content);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        bufferedReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

四、原文件基础上拼接内容

把这个套进去

new FileOutputStream(new File("a.txt"),true);

五、读写xml文件

<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
		<dependency>
			<groupId>org.dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>2.1.3</version>
		</dependency>

XMLFile.java

package file;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.tree.DefaultCDATA;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;

/**
 * Create by zjg on 2022/10/12
 */
public class XMLFile {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream=null;
        try {
            File file=new File("pom.xml");
            fileInputStream = new FileInputStream(file);
            byte[]bytes=new byte[(int) file.length()];
            fileInputStream.read(bytes);
            String s = new String(bytes);
            Document document = DocumentHelper.parseText(s);
            Element rootElement = document.getRootElement();
            //添加属性
            rootElement.addAttribute("s","ssr");
            String s1 = rootElement.attributeValue("s");//获取属性
            System.out.println(s1);
            //rootElement.remove(new DOMAttribute(new QName("s")));//删除属性
            //遍历属性
            List<Attribute> attributes = rootElement.attributes();
            for(Attribute attribute:attributes){
                System.out.println(attribute.getName());
            }
            //添加dependency1元素
            Element dependencies = rootElement.element("dependencies");
            String dependency="\n\t\t\t<groupId>com.sd.jn</groupId>\n" +
                            "\t\t\t<artifactId>sks</artifactId>\n" +
                            "\t\t\t<version>1.2.1</version>\n";
            Element dependencyElement = dependencies.addElement("dependency1");
            dependencyElement.add(new DefaultCDATA(dependency));
            //dependencies.remove(dependencyElement);删除dependency1元素
            //遍历dependencies
            Iterator<Element> elementIterator = dependencies.elementIterator("dependency");
            while (elementIterator.hasNext()){
                Element element = elementIterator.next();
                System.out.println(element.getName());//标签名
                System.out.println(element.getStringValue());//标签值
            }
            //生成新文件
            String newXml = document.asXML();
            System.out.println(newXml);
            fileOutputStream=new FileOutputStream(file);
            fileOutputStream.write(newXml.getBytes(StandardCharsets.UTF_8));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


总结

换汤不换药
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值