英文:
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 = "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();
// 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论