我想要完成的是读取文件目录并打印 pdf 的链接,但更重要的是某些 PDF 以 123456_2018-01.pdf、456234_2018-01a.pdf 或 123456_2018- 结尾01 后面跟着一些字母。我不知道应该使用什么表达式来捕获该月的所有 pdf。
for (File obj : contentsOfDirectory) {
if (obj.isFile()) {
if (!obj.getName().substring(0, 2).equals("._")) {
String file = "this is the file directory";
String pdfBills = file + obj.getName().toString();
String year = pdfBills.substring(pdfBills.lastIndexOf("_") + 1);
if (obj.getName().toString().endsWith("01.pdf")) {
%>
<li><a href=<%=pdfBills%>>January <%=year%></a><br> <%
} else if (obj.getName().toString().endsWith("02.pdf")) {
%>
<li><a href=<%=pdfBills%>>February <%=year%></a><br> <%
我尝试过使用 .matches(^01*.pdf)
,但它从未在页面上显示链接,这让我相信我使用不正确。
最佳答案
这看起来像 regex对我来说有点问题所以使用 Pattern类(class)。通过积极匹配我们想要的内容,它会隐式忽略不符合要求的文件(例如您的 ._
示例)
final Pattern p = Pattern.compile(".*_(\\d{4})-(\\d{2})\\.pdf$");
for (File obj : contentsOfDirectory) {
if (obj.isFile())
String file = "this is the file directory";
String pdfBills = file + obj.getName().toString();
Matcher m = p.matcher(pdfBills);
if (m.matches()) {
int year = Integer.parseInt(m.group(1));
int month = Integer.parseInt(m.group(2));
// ... do stuff with year and month
}
关于Java读取文件目录并创建pdf的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58738624/