gpt4 book ai didi

Java 全局文件数组在方法之后丢失下标

转载 作者:行者123 更新时间:2023-12-01 21:30:14 25 4
gpt4 key购买 nike

我正在一个Java程序中工作,我希望能够在退出FileArray获取其下标值的方法后使用FileArray的下标。我已在其类的公共(public)范围内声明了 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();
}

}

最佳答案

您正在创建 variable shadowreadFiles 中使用

File[] listOfFiles = folder_directory.listFiles();

将其更改为类似的内容

listOfFiles = folder_directory.listFiles();

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com