此程序列出了扩展名为 .brd
的文件的内容,我使用“glob”“.brd”
作为 Files.newDirectoryStream< 的第二个参数来完成此操作
。效果很好,表明 Windows 文件模式是可以接受的。但没有。
但是我也想列出没有扩展名的文件。对于我尝试过的任何 glob 模式(Windows 文件名模式),我都无法得到它。
显然,glob不被解释为 Windows 文件名模式,也不被解释为正则表达式。
我尝试过这些不同的 Windows 模式。
-如果我使用 glob“*.”,我应该只获取没有扩展名的文件(这就是我想要的),但我没有得到任何文件。
-如果我使用 glob“* .*”,我应该获取所有文件,但我只获取确实具有扩展名的文件。 (这仅供引用。)(请注意:glob 应该是“星点星”,没有空格;格式问题。)
-如果我使用 glob“*”,我会得到每个文件,这与 Windows 模式一致。 (仅供引用)
什么 glob 模式可以只获取没有扩展名的文件进行处理? 或者,我可以使用什么正则表达式来做到这一点?
package listdirectorycontents;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.*;
import java.io.IOException;
import java.util.Scanner;
public class ListDirectoryContents {
static DirectoryStream<Path> directoryStream;
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\Users\\Dov\\My Documents\\boards");
String output, L;
directoryStream = Files.newDirectoryStream(path, "*.brd");
System.out.println("\n" + path + " directory contains:");
for(Path aFile : directoryStream) {
output = "";
try{
try
(FileInputStream inputFile = new FileInputStream(aFile.toString());
Scanner scanner = new Scanner(inputFile)
)
{
for(int i = 0; i < 4; i++)
if(scanner.hasNext())
scanner.next();
if(scanner.hasNext()){
L = scanner.next();
while(L.length() == 4){
output += L;
L = scanner.next();
}
System.out.println(output);
}
}
}
catch(FileNotFoundException e){System.out.println("\t*Not a file? " + e);}
}
}
}
glob 的文档包含此有限的帮助(在 getPathMatcher
下):
文件系统实现支持“glob”和“regex”语法,并且可能支持其他语法。比较语法组件的值时不考虑大小写。
当语法为“glob”时,则使用类似于正则表达式但语法更简单的有限模式语言来匹配路径的字符串表示形式。例如...
也许答案是切换到 FileVisitor
,但我希望尽可能少地重写。
* 解决方法 *
directoryStream = Files.newDirectoryStream(path); // to get all files; no globs
...
for(Path aFile : directoryStream)
{
if(aFile.toString().endsWith("brd") || ! aFile.toString().contains("."))
{
...
}
}
最佳答案
Java 的 globbing 引擎与 POSIX globbing 一致,其工作方式与 cmd.exe
略有不同(但更合理)。通配符。 POSIX 通配符与 '.'
的事实是一致的。字符在 POSIX 文件名中并不特殊,这与从 DOS 继承的 Windows 传统相反。因此,'*'
glob 模式中的可以匹配零个或多个字符,包括任意数量的 '.'
字符,以及 '.'
以 glob 模式出现必须匹配 '.'
在文件名中。 FileSystem.getPathMatcher(String) 的 API 文档涵盖了所有这些内容。顺便说一下,具体来说:
*.* Matches file names containing a dot
和
The * character matches zero or more characters of a name component without crossing directory boundaries.
请注意,没有记录 '.'
的特殊处理性格。
虽然您可以将单个非点字符与 glob 模式匹配(即 "[!.]"
),但 glob 语法中没有子模式重复运算符。
另一方面,您可以使用正则表达式轻松匹配不带扩展名的文件名。这个模式可以做到:"[^.]*"
,假设您使用 Matcher.matches()
(与 Matcher.find()
相反,它不需要整个字符串与模式匹配。)
关于java - 如何使用带有 newDirectoryStream 的 glob 来仅列出没有扩展名的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26554746/