如何使用Java将文件列表获取到数组中?

huangapple go评论63阅读模式
英文:

How to get file list in array using java?

问题

我正在尝试从目录中获取文件名并作为数组

我希望

    List<String> list = ["c:/MyFolder/file1.txt", "c:/MyFolder/file2.txt"];

然后我可以这样获取它们

    println list[0] //c:/MyFolder/file1.txt
    println list[1] //c:/MyFolder/file2.txt

我如何从这段代码中获得文件名数组

import java.io.File;

public class FileListFromFolder {
     
    public static void main(String a[]){
        File file = new File("C:/MyFolder/");
        String[] fileList = file.list();
        for(String name:fileList){
            System.out.println(name);
        }
    }
}

谢谢
英文:

i`m trying to get file name from directory as array.

i want:

List&lt;String&gt; list = [&quot;c:/MyFolder/file1.txt&quot;, &quot;c:/MyFolder/file2.txt&quot;];

Then i can get then like:

println list[0] //c:/MyFolder/file1.txt
println list[1] //c:/MyFolder/file2.txt

how can i have filenames is array from this code?

import java.io.File;


public class FileListFromFolder {
     
    public static void main(String a[]){
        File file = new File(&quot;C:/MyFolder/&quot;);
        String[] fileList = file.list();
        for(String name:fileList){
            System.out.println(name);
        }
    }
}

Thank you

答案1

得分: 0

以下是您需要的翻译:

这可能会对您有所帮助

    public class FileListFromFolder {
     
        public static void main(String a[]) {
          File file = new File("C:/MyFolder/");
          String[] fileList = file.list();
          List<String> arrayToList = Arrays.asList(fileList);
          System.out.println(arrayToList);
       }
    }
英文:

This might help you

public class FileListFromFolder {
 
    public static void main(String a[]) {
      File file = new File(&quot;C:/MyFolder/&quot;);
      String[] fileList = file.list();
      List&lt;String&gt; arrayToList = Arrays.asList(fileList);
      System.out.println(arrayToList);
   }
}

答案2

得分: 0

      文件 file = new 文件("C:/我的文件夹/");
      文件[] 文件列表 = file.获取文件列表();
      对于 (文件 f : 文件列表) {
         System.out.println(f.获取名称());
      }
英文:
      File file = new File(&quot;C:/MyFolder/&quot;);
      File[] fileList = file.listFiles();
      for(File f:fileList){
         System.out.println(f.getName());
      }


This is the way to iterate over a list of files in directory and to print their names.

huangapple
  • 本文由 发表于 2020年8月27日 04:21:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63605203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定