java - 错误地返回数组,用最后一项覆盖所有

标签 java arrays return

我看过一些类似的帖子,但与我遇到的问题不同。我想要做的是调用一个函数,该函数显示编号为

的文件的名称
1- File1.txt,
2- File2.txt
..

这按预期工作。问题是我需要在另一个数组中返回这些文件的路径。当我在 forSystem.out.print(arrayRutasFicheros[j]) 时,它会正确显示所有路径。但是当我尝试从其他函数访问 arrayRutasFicheros[j] 时。它只是覆盖所有路径并只显示最后一个路径。

public static String[] listarArchivos() throws IOException{

    File[] listadoDeFiles = documento.listFiles();
    File[] arrayFicheros = null;
    String[] arrayRutasFicheros = null;

    if(documento.exists() ) {

        for (int k=0; k< listadoDeFiles.length ;k++) {

            File ficheroRuta = listadoDeFiles[k];

            File fichero = new File(documento.getPath() + sep+ ficheroRuta.getName());

            if(fichero.isFile()==true) {

                arrayFicheros =new File[] {fichero};

                System.out.println( k + " - " + ficheroRuta.getName());

                for(int j= 0; j<arrayFicheros.length; j++) {

                    arrayRutasFicheros =  new String[] {arrayFicheros[j].getPath()};

                    //here it works and it display all the path
                    System.out.println(arrayRutasFicheros[j]);
                }   

            }   
        }       
    }

    return arrayRutasFicheros;
}

public static muestraUnArchivo() throws IOException {

    String [] Fichero =listarArchivos();

    for(int k=0; k<Fichero.length; k++) {

    //here just the last one
    System.out.print(Fichero[k]);       
    }
}

预期:

-E:\Eclipse\Files\File1.txt   
-E:\Eclipse\Files\File2.txt  
-E:\Eclipse\Files\File3.txt   

输出:

-E:\Eclipse\Files\File3.txt

最佳答案

你的数组在循环的每次迭代中重新创建,它也在一个长度为 1 的数组上.您需要一个动态结构来存储字符串路径,因为您事先不知道有多少。此外,您不需要继续创建单个元素数组;使用List<String> .类似的东西,

public static String[] listarArchivos() throws IOException {
    List<String> al = new ArrayList<>();
    if (documento.exists()) {
        File[] listadoDeFiles = documento.listFiles();
        for (File ficheroRuta : listadoDeFiles) {
            File fichero = new File(documento.getPath() 
                    + sep + ficheroRuta.getName());
            if (fichero.isFile()) {
                al.add(fichero.getPath());
            }
        }
    }

    return al.toArray(new String[0]);
}

关于java - 错误地返回数组,用最后一项覆盖所有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61106769/

相关文章:

java - 无法在 RStudio 中加载 rJava

java - move 文件而不释放锁

java - 从数组中随机播放特定对象

c - 如何对数组的一个子集进行平均并将结果存储在另一个数组中?

ruby-on-rails - 是否有可能在 rails(或 ruby​​ 的其他地方)中阻止 block 返回?返回数组中的 50,000 条记录需要一段时间

java - 为什么我无法在 Java/Kotlin 中格式化字符串

java - 如何使用 Java Gson 库转换动态 JSON 响应

javascript - 将数字插入数组

python - 这两个代码有什么区别?

Javascript:检查对象,如果[条件],则返回x