如何使用 `Paths.get` 获取以特定字符开头的文件的路径?

huangapple go评论137阅读模式
英文:

How to get (Paths.get) one file with a filename starting with a certain character?

问题

以下是您要求的翻译内容:

我正在一个使用Java 8的项目中工作,在该项目中,我使用Paths类从特定位置读取一个文件,一切正常。
这是我的代码:

String inputDir = "src/main/distribution/in";

String fileName = "my_file.txt";

Path inputFile = Paths.get(inputDir, fileName);

// 读取文件行... 没问题

现在我的问题是,这个文件每天都会更改,格式如下:filename.txt_date,所以每天我只会找到一个名为my_file.txt_02082020这样的文件。

所以我的问题是,我如何通过检查文件名是否以my_file.txt_开头来读取我的文件?

您对如何实现这一点有什么建议吗?

提前谢谢。

英文:

im working in java 8 project where i read one file from specific location using Paths class and all works fine.
this is my code :

String inputDir = "src/main/distribution/in";

String fileName = "my_file.txt";

Path inputFile = Paths.get(inputDir, fileName);

// reading file lines... is OK

now my issue is this file will be changed each day with the following format filename.txt_date
so each day i will find only one file with name like this : my_file.txt_02082020.

so my question is how i can read my file only by checking if the file name starts with "my_file.txt_"?

do you have any suggestion to do this ?

Thanks in advance.

答案1

得分: 2

Path类带有流(streams)功能,因此您可以在文件列表上进行过滤:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import java.io.File;
import java.nio.file.Path;

String inputDir = "src/main/distribution/in";
String fileName = "my_file.txt";
Optional<Path> file = Files.list(Paths.get(inputDir))
    .filter(p -> p.getFileName().toFile().getName().startsWith(fileName))
    .findFirst();
if (file.isPresent()) {
    Path foundFile = file.get();
    File asFile = foundFile.toFile();
    // 业务逻辑在这里
}

编辑:由于只有一个文件,所以使用了findFirst而不是forEach。

编辑2:显然,Path.startsWith()的工作方式与String不同。将其更改为获取文件名作为字符串(通过File)以验证其名称。

英文:

Path comes with streams so you can filter on the list of files:

import java.nio.file.Files;
import java.nio.file.Paths;

String inputDir = &quot;src/main/distribution/in&quot;;
String fileName = &quot;my_file.txt&quot;;
Optional&lt;Path&gt; file=Files.list(Paths.get(inputDir))
	.filter(p-&gt;p.getFileName().toFile().getName().startsWith(fileName))
	.findFirst();
if(file.isPresent())
{
    Path foundFile=file.get();
    File asFile=foundFile.toFile();
    // business logic here
}

EDIT: used findFirst instead of forEach as there is only one file.

EDIT2: apparently Path.startsWith() does not work the same way as String. Changed it to get the filename as a string (via File) to verify its name.

huangapple
  • 本文由 发表于 2020年8月20日 17:58:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63502647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定