java中文件的写入和读出

发布时间:2020-06-10 10:31:04 作者:Leah
来源:亿速云 阅读:222

这篇文章给大家分享的是java中文件的写入和读出的方法。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

一、文档读取

1、将文件读取为String

public static String TxtToString(File file) {
    String result = "";
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        //构造一个BufferedReader类来读取文件
        String s = null;
        while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
            result = result + "\n" + s;
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

2、将文件读取为List集合(按行)

public static List<String> TxtToStringList(File file) {
    List<String> result = new ArrayList<>();
    try {
        if (!file.exists()){
            return null;
        }
        BufferedReader br = new BufferedReader(new FileReader(file));
        //构造一个BufferedReader类来读取文件
        String s = null;
        while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
            result.add(s);
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

二、Java存储文件

1、将list按行写入到txt文件中

public static void writeFileContext(List<String> strings) throws Exception {
    File file = new File("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\WordLibrary_index");
    //如果没有文件就创建
    if (!file.isFile()) {
        file.createNewFile();
    }
    BufferedWriter writer = new BufferedWriter(new FileWriter
    ("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\WordLibrary_index"));
    for (String l:strings){
        writer.write(l + "\r\n");
    }
    writer.close();
}

2、按照名字将string类型的集合存入文件

public static void writeFileContext_Find(List<String> strings,String name) throws Exception {
    File file = new File("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\wordIndex");
    //如果没有文件就创建
    if (!file.isFile()) {
        file.createNewFile();
    }
    BufferedWriter writer = new BufferedWriter(new FileWriter
    ("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\wordIndex\\"+name));
    for (String l:strings){
        writer.write(l + "\r\n");
    }
    writer.close();

3、将Sting类型的list集合按文件地址存储

public static void writeFileContext_Found(List<String> strings,String filename) throws Exception {
    File file = new File(filename);
    //如果没有文件就创建
    if (!file.isFile()) {
        file.createNewFile();
    }
    BufferedWriter writer = new BufferedWriter(new FileWriter
    ("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\file_index\\"+file.getName()));
    for (String l:strings){
        writer.write(l + "\r\n");
    }
    writer.close();
}

关于java中文件的写入和读出就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 文件操作写入和读出结构体--修改文件信息
  2. java读取和写入文件时乱码怎么解决

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java 文件写入和读出 ava

上一篇:python爬虫常用模块有哪些

下一篇:aria2下载工具命令行和图形化界面使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》