我正在一个Java程序中工作,我想在它退出FileArray获取下标值的方法后使用FileArray的下标。我已经在其类的公共范围内声明了FileArray,但是,一旦FileArray退出给出下标值的方法,则FileArray变为null,不能用来表示它在先前方法中获得的值。我如何获得这个FileArray来保持其下标在整个类中的持久性。任何帮助将不胜感激。顺便说一下,FileArray的名称是“ listOfFiles”。

package prototype_1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;

public class FileExtensionReader {

// Current folder/directory-path used for testing:
// C:\Users\Christopher\Desktop\grupeeTestFolder

private Scanner sc; // Declare Scanner Object
private String bulkFolderPath; // Declare String representing path to folder
                                // that contains files
private File[] listOfFiles;

public void readFiles() { // Reads and saves filenames in Array
    System.out.println("Please enter folder/directory filepath"); // Prompt
                                                                    // to
                                                                    // enter
                                                                    // Folder/Directory
                                                                    // path
    sc = new Scanner(System.in); // Create Scanner Object
    bulkFolderPath = sc.nextLine(); // String representing folder/directory
                                    // path to folder/directory containing
                                    // files
    File folder_directory = new File(bulkFolderPath); // File Object of bulk
                                                        // folder
    File[] listOfFiles = folder_directory.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()) {
            System.out.println("File::: " + listOfFiles[i].getName());
        } else if (listOfFiles[i].isDirectory()) {
            System.out.println("Directory " + listOfFiles[i].getName());
        }
    }

    System.out.println("If this prints, it means 'listOfFiles' FileArray"
            + " is consistent within this method, and the number printed " + "represents the number of "
            + "files found" + "\n" + "by the program. " + "Number: " + listOfFiles.length + "     "
            + listOfFiles[0]);
}

public void groupFilenames() {
    System.out.println("Number again: " + listOfFiles);
}

public static void main(String[] args) {
    FileExtensionReader FER1 = new FileExtensionReader();
    FER1.readFiles();
    FER1.groupFilenames();
}


}

最佳答案

您正在使用readFiles在中创建variable shadow

File[] listOfFiles = folder_directory.listFiles();


将其更改为

listOfFiles = folder_directory.listFiles();

关于java - Java全局文件数组使方法后的下标丢失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37516398/

10-10 21:10