显示当前(或指定)目录中所有.txt文档的名称
所以我有以下代码(已经从教程中无耻地复制,因此我可以对基础进行排序),其中它要求玩家加载他们的游戏(基于文本的冒险游戏),但我需要一种方式来显示所有保存在目录中的游戏。 我无需担心当前目录。 这是我的代码:
public void load(Player p){ Sleep s = new Sleep(); long l = 3000; Scanner i = new Scanner(System.in); System.out.println("Enter the name of the file you wish to load: "); String username = i.next(); File f = new File(username +".txt"); if(f.exists()) { System.out.println("File found! Loading game...."); try { //information to be read and stored String name; String pet; boolean haspet; //Read information that's in text file BufferedReader reader = new BufferedReader(new FileReader(f)); name = reader.readLine(); pet = reader.readLine(); haspet = Boolean.parseBoolean(reader.readLine()); reader.close(); //Set info Player.setUsername(name); Player.setPetName(pet); Player.setHasPet(haspet); //Read the info to player System.out.println("Username: "+ p.getUsername()); s.Delay(l); System.out.println("Pet name: "+ p.getPetName()); s.Delay(l); System.out.println("Has a pet: "+ p.isHasPet()); } catch(Exception e){ e.printStackTrace(); } } }
File currentDirectory = new File(currentDirectoryPath); File[] saveFiles = currentDirectory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".txt"); } });
您可以先获取目录的File
对象:
File ourDir = new File("/foo/bar/baz/qux/");
然后通过检查ourDir.isDirectory()
您可以确保不会意外地尝试处理文件。 您可以通过回退到另一个名称或抛出exception来处理此问题。
然后,您可以获得一个File
对象数组:
File[] dirList = ourDir.listFiles();
现在,您可以使用getName()为每个迭代它们并执行您需要的任何操作。
例如:
ArrayList fileNames=new ArrayList<>(); for (int i = 0; i < dirList.length; i++) { String curName=dirList[i].getName(); if(curName.endsWith(".txt"){ fileNames.add(curName); } }
这应该工作:
File folder = new File("path/to/txt/folder"); File[] files = folder.listFiles(); File[] txtFiles = new File[files.length]; int count = 0; for(File file : files) { if(file.getAbsolutePath().endsWith(".txt")) { txtFiles[count] = file; count++; } }
它应该是非常自我解释的,你只需要知道folder.listFiles()
。
要减少txtFiles[]
数组,请使用Array.copyOf
。
File[] finalFiles = Array.copyOf(txtFiles, count);
来自文档:
使用false复制指定的数组,截断或填充(如果需要),以使副本具有指定的长度。