欢迎光临
我们一直在努力

java中如何实现文件的读入与读出

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 + "
" + s;
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

2、将文件读取为List集合(按行)(免费视频教程分享:java免费视频教程)

public static List TxtToStringList(File file) {
    List 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 strings) throws Exception {
    File file = new File("D:IntellijIDEAProjectKeChenSheJidataWordLibrary_index");
    //如果没有文件就创建
    if (!file.isFile()) {
        file.createNewFile();
    }
    BufferedWriter writer = new BufferedWriter(new FileWriter
    ("D:IntellijIDEAProjectKeChenSheJidataWordLibrary_index"));
    for (String l:strings){
        writer.write(l + "
");
    }
    writer.close();
}

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

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

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

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

相关文章教程推荐:java快速入门

分享本文到
赞(0)
未经允许不得转载:爱分享 » java中如何实现文件的读入与读出

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

爱分享,生活常用知识教程百科分享、学习、交流平台

爱分享精选好货商城