我需要帮助从目录中的所有文件中读取数据

时间:2017-07-31 10:02:08

标签: java file io

我有一段代码可以遍历目录中的所有文件。 但是现在我被困在将文件内容读入String对象中。

public String filemethod(){
        if (path.isDirectory()) {
            files = path.list();
            String[] ss;
            for (int i = 0; i < files.length; i++) {
                ss = files[i].split("\\.");
                if (files[i].endsWith("txt"))
                    System.out.println(files[i]);
            }
        }

    return String.valueOf(files);
}

3 个答案:

答案 0 :(得分:2)

面对类似的问题并且不久前写了一段代码。这将读取目录中所有文件的内容。

可能需要根据您的文件目录进行调整,但需要经过测试和验证的代码。希望这有帮助:)

package FileHandling;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;

public class BufferedInputStreamExample {

    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;

    public void readFile(File folder) {
        ArrayList<File> myFiles = listFilesForFolder(folder);

        for (File f : myFiles) {
            String path = f.getAbsolutePath();

            //Path of the file(Optional-You can know which file's content is being printed)
            System.out.println(path);
            File infile = new File(path);

            try {
                fis = new FileInputStream(infile);
                bis = new BufferedInputStream(fis);
                dis = new DataInputStream(bis);

                while (dis.available() != 0) {
                    String line = dis.readLine();
                    System.out.println(line);
                }

            } catch (IOException e) {
            } finally {
                try {
                    fis.close();
                    bis.close();
                    dis.close();
                } catch (Exception ex) {
                }
            }
        }
    }

    public ArrayList<File> listFilesForFolder(final File folder){
        ArrayList<File> myFiles = new ArrayList<File>();

        for (File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                myFiles.addAll(listFilesForFolder(fileEntry));
            } else {
                myFiles.add(fileEntry);
            }
        }
        return myFiles;
    }
}

主要方法

package FileHandling;

import java.io.File;

public class Main {

public static void main(String args[]) {

    //Your directory here
    final File folder = new File("C:\\Users\\IB\\Documents\\NetBeansProjects\\JavaIO\\files");

    BufferedInputStreamExample bse = new BufferedInputStreamExample();
    bse.readFile(folder);

    }
}

答案 1 :(得分:1)

我会使用以下代码:

<li>
  <div id="mybtn1">
    <h1>Title </h1>
    <img src="logo1.png" />
    <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. R</p>
    <svg class="icon-arrow" viewBox="0 0 137.648 256">
      <polygon class="line" points="0,246.161 9.843,256 137.648,128.2 137.451,128.003 137.648,127.806 9.843,0 0,9.833 118.167,127.996 " style="stroke-width:2"></polygon>
    </svg>
  </div>
</li>

然后您需要的是一个定义哪些文件与您的用例相关的方法(例如txt)

public static Collection<File> allFilesInDirectory(File root) {
    Set<File> retval = new HashSet<>();
    Stack<File> todo = new Stack<>();
    todo.push(root);
    while (!todo.isEmpty()) {
        File tmp = todo.pop();
        if (tmp.isDirectory()) {
            for (File child : tmp.listFiles())
                todo.push(child);
        } else {
            if (isRelevantFile(tmp))
                retval.add(tmp);
        }
    }
    return retval;
}

获得所有文件后,您可以轻松地在Scanner中轻松获取所有文本

public static boolean isRelevantFile(File tmp) {
    // get the extension
    String ext = tmp.getName().contains(".") ? tmp.getName().substring(tmp.getName().lastIndexOf('.') + 1) : "";
    return ext.equalsIgnoreCase("txt");
}

现在,使用这些方法,您可以轻松地从整个目录中提取所有文本。

public static String allText(File f){
    // \\z is a virtual delimiter that marks end of file/string
    return new Scanner(f).useDelimiter("\\z").next();
}

答案 2 :(得分:1)

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;


public class ReadDataFromFiles {
    static final File DIRECTORY = new File("C:\\myDirectory");
    public static void main(String[] args) throws IOException {
        StringBuilder sb = new StringBuilder();
        //append content of each file to sb
        for(File f : getTextFiles(DIRECTORY)){
            sb.append(readFile(f)).append("\n");
        }
        System.out.println(sb.toString());
    }
    // get all txt files from the directory
    static File[] getTextFiles(File dir){
        FilenameFilter textFilter = (File f, String name) -> name.toLowerCase().endsWith(".txt");
        return dir.listFiles(textFilter);
    }
    // read the content of a file to string
    static String readFile(File file) throws IOException{
        return new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())), StandardCharsets.UTF_8);
    }
}