【问题标题】:is there a way to use the file path instead of file name in BufferedReader?有没有办法在 BufferedReader 中使用文件路径而不是文件名?
【发布时间】:2022-11-22 01:50:34
【问题描述】:

我想在 BufferedReader 中添加路径而不是文件名? 我想使用该路径,因为我希望代码在该特定文件夹中获取名称为“audit”的任何文件。

所以我目前正在使用下面的这种方法,但它只有在我添加绝对路径时才有效。

`

public static void main(String[] args)
        throws IOException {
    List<String> stngFile = new ArrayList<String>();
    BufferedReader bfredr = new BufferedReader(new FileReader
            ("file path"));



    String text = bfredr.readLine();
    while (text != null) {
        stngFile.add(text);
        text = bfredr.readLine();
    }
    bfredr.close();
    String[] array = stngFile.toArray(new String[0]);

    Arrays.toString(array);
    for (String eachstring : array) {
         System.out.println(eachstring);
    }

}

`

我是编程新手,非常感谢任何帮助。提前致谢。

【问题讨论】:

  • 您需要循环打开与您的模式匹配的每个文件。

标签: java path bufferedreader


【解决方案1】:

FileReader 还有一个接受文件的构造函数。您可以使用 URI 或路径字符串创建文件对象。您可以使用 FileFilter 或只检查每个文件是否与您提供的名称匹配,我会这样做:

要获取文件夹中的所有文件,您可以使用folder.listFiles()
然后您可以使用file.getName().contains("audit") 来检查文件名是否包含“audit”。

请注意,这是区分大小写的,要忽略大小写,您只需使用file.getName().toLowerCase().contains("audit")(确保您在此处检查的字符串,在本例中为“audit”,始终为小写)。

正如 g00se 所指出的,您还必须使用 file.isFile() 检查文件是否实际上是文件而不是目录

然后在一个循环中,您只需分别读出符合上述条件的每个文件的内容。

如果您还需要所有子文件夹中的文件,请参阅this post

例子:

public static void main(String[] args) throws IOException {
    File folder = new File("C:\MyFolder"); // the folder containing all the files you are looking for
    for (File file : folder.listFiles()) { // loop through each file in that folder
        if (file.getName().contains("audit") && file.isFile()) { // check if it contains audit in its name
            // your previous code for reading out the file content
            BufferedReader bfredr = new BufferedReader(new FileReader(file));
            List<String> stngFile = new ArrayList<String>();
            String text = bfredr.readLine();
            while (text != null) {
                stngFile.add(text);
                text = bfredr.readLine();
            }
            bfredr.close();
            String[] array = stngFile.toArray(new String[0]);
            
            Arrays.toString(array);
            for (String eachstring : array) {
                 System.out.println(eachstring);
            }
        }
    }

}

【讨论】:

  • if (file.getName().contains("audit") &amp;&amp; file.isFile())过滤器也可以用
  • 你说得对,让我调整一下。
猜你喜欢
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 2015-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多