[英]java listing the txt files in sub folders
嗨,我有一個 jlist,目前它正在查看一個文件夾 + 子文件夾...現在我想更改它以查看子文件夾中的文件。 請在下面找到我當前使用的代碼:
jList1.setModel(new javax.swing.AbstractListModel()
{
File folder = new File ("/Assignment_Datex/message_outbox/");
File[] listofFiles = folder.listFiles();
// @Override
public int getSize()
{ return listofFiles.length; }
// @Override
public Object getElementAt(int i)
{ return listofFiles[i];}
}
);
現在,正如您在屏幕截圖中看到的那樣,Jlist 只查看文件夾而不是其中的文件......請幫忙?
如果你想顯示某個根文件夾下的所有文件和文件夾,那么你應該嘗試這樣的事情......
我不能在這里生成完整的代碼,但這是一個原型:
void addFilesToList(File folder){
File[] listofFiles = folder.listFiles();
for(File file:listofFile){
if(file.isFile()) // --- file
list.add(file.getName());
else{ // --- folder
addFileToList(file);
}
}
}
上述代碼未經測試,因此可能需要對其進行修改以滿足您的需要。
@Harry Joy 是對的。 此外,您還可以使用 jakarta 項目中的 FindFile。 它可以節省您的時間。
我認為這是讀取文件夾和子文件夾中 all.txt 文件的好方法
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}
現在你有一個文件列表,你可以對它進行一些處理!
您創建一個構造函數來初始化您的 class,然后放在那里(經過測試和工作)
// initialize the class variable
listofFiles = new ArrayList();
// initialize with the path
File f = new File("/home/albertmatyi/Work/python/");
// create a temporary list to work with
LinkedList files = new LinkedList();
// fill it with the contents of your path
files.addAll(Arrays.asList(f.listFiles()));
while (!files.isEmpty()) {
// keep removing elements from the list
f = files.pop();
// if it is a directory add its contents to the files list
if (f.isDirectory()) {
files.addAll(Arrays.asList(f.listFiles()));
// and skip the last if
continue;
}
// check if it's a text file, and add it to listofFiles
if (f.getName().endsWith(".txt"))
listofFiles.add(f);
}
注意:我已將 listofFiles 的類型更改為ArrayList<File>
,必須在構造函數中使用以下命令對其進行初始化:
listofFiles = new ArrayList<File>();
這允許更輕松地操作數據 - 當需要添加更多文本文件時,無需手動分配更大的空間
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.