旗下导航:搜·么
当前位置:网站首页 > JAVA教程 > 正文

java中怎样完成文件的读入与读出【JAVA教程】,java,实现,文件,读入,读出

作者:搜教程发布时间:2019-12-28分类:JAVA教程浏览:74评论:0


导读:一、文档读取1、将文件读取为StringpublicstaticStringTxtToString(Filefile){Stringresult...

一、文档读取

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鸠合(按行)(免费视频教程分享:java免费视频教程)

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疾速入门

以上就是java中怎样完成文件的读入与读出的细致内容,更多请关注ki4网别的相干文章!

标签:java实现文件读入读出


欢迎 发表评论: