如何使用java搜索文件中的日期格式20180603?
我有一个文件,其中的单词用“|”分隔。这里我需要搜索日期“20180603”。但是,我无法硬编码要搜索的值。日期格式是固定的YYYYDDMM,日期可以是任何内容。 我需要将这里的日期转换为今天的日期(系统日期) 我正在粘贴外部文件的外观(仅在相关值周围添加了星号以强调): 我试过很多问题,但都没有成功 下面是我试过的代码如何使用java搜索文件中的日期格式20180603?,java,date,filereader,Java,Date,Filereader,我有一个文件,其中的单词用“|”分隔。这里我需要搜索日期“20180603”。但是,我无法硬编码要搜索的值。日期格式是固定的YYYYDDMM,日期可以是任何内容。 我需要将这里的日期转换为今天的日期(系统日期) 我正在粘贴外部文件的外观(仅在相关值周围添加了星号以强调): 我试过很多问题,但都没有成功 下面是我试过的代码 public class ReadFile { public static void main(String[] args) throws IOException {
public class ReadFile {
public static void main(String[] args) throws IOException {
File f1= new File("C:/Users/kumar.sushobhan/Desktop/ESPYTR_Big_file_EXEC.dat");
//File f1= new File("C:/Users/kumar.sushobhan/Desktop/h.txt");
String words[]= null;
FileReader fr= new FileReader(f1);
BufferedReader br= new BufferedReader(fr);
String s;
int c = 0;
String regex= "\\d{4}\\d{2}\\d{2}";
while((s= br.readLine())!=null)
{
words= s.split("|");
for(String word: words)
{
//System.out.println(word);
if(word.equals(regex))
{
c++;
}
}
}
System.out.println(c);
fr.close();
}
}
我希望读取快照中的日期并将其更改为当前系统日期。使用字符串中的contains方法
s、 包含(“20180603”)您可以使用如下正则表达式
String regex = "(19|20)[0-9][0-9](0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|30|31)";
它并不完美,但它将匹配大多数日期。例如,它将删除超过12个月的日期。此外,它将在2099年之前有效。它不考虑日期规则,比如六月有30天。它将与1-31天之间的任何日期匹配
您不能对日期使用
equals
。您必须使用Pattern.matches(regex,string)
这里有一个基本算法,它将查找管道分隔的文件,用当前日期替换“看起来像”日期的值,然后将所有内容写回新文件。它使用您在问题中描述的yyyydmm
格式,但它可能应该是YYYYMMDD
,我已经注意到您需要在哪里进行更改。这在日期验证和错误处理方面减少了一些细节,以尽量使其相对简短,但我已经过度评论,试图解释一切:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateReplacer
{
private static final Pattern DATE_MATCHER =
Pattern.compile("(?:(?:19|20)[0-9]{2})([0-9]{2})([0-9]{2})");
public static void main(String... args)
throws Exception
{
// These are the paths to our input and output files
Path input = Paths.get("input.dat");
Path output = Paths.get("output.dat");
// We need to get today's date in YYYYDDMM format, so we create a
// DateFormatter for that. If it turns out that your date format is
// actually YYYYMMDD, you can just use DateFormatter.BASIC_ISO_DATE
// instead.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyddMM");
String todaysDate = LocalDate.now().format(formatter);
// Use try-with-resources to create a reader & writer
try (BufferedReader reader = Files.newBufferedReader(input);
BufferedWriter writer = Files.newBufferedWriter(output)) {
String line;
// Read lines until there are no more lines
while ((line = reader.readLine()) != null) {
// Split them on the | character, notice that it needs to be
// escaped because it is a regex metacharacter
String[] columns = line.split("\\|");
// Iterate over every column...
for (int i = 0; i < columns.length; i++) {
// ... and if the value looks like a date ...
if (isDateLike(columns[i])) {
// ... overwrite with today's date.
columns[i] = todaysDate;
}
}
// Re-join the columns with the | character and write it out
writer.write(String.join("|", columns));
writer.newLine();
}
}
}
private static boolean isDateLike(String str)
{
// Avoid the regular expression if we can
if (str.length() != 8) {
return false;
}
Matcher matcher = DATE_MATCHER.matcher(str);
if (matcher.matches()) {
// If it turns out that your date format is actually YYYYMMDD
// you will need to swap these two lines.
int day = Integer.parseInt(matcher.group(1), 10);
int month = Integer.parseInt(matcher.group(2), 10);
// We don't need to validate year because we already know
// it is between 1900 and 2099 inclusive
return day >= 1 && day <= 31 && month >= 1 && month <= 12;
}
return false;
}
}
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.time.LocalDate;
导入java.time.format.DateTimeFormatter;
导入java.util.regex.Matcher;
导入java.util.regex.Pattern;
公共类日期替换程序
{
私有静态最终模式日期匹配器=
模式编译((?:(?:19 | 20)[0-9]{2})([0-9]{2})([0-9]{2}”);
公共静态void main(字符串…参数)
抛出异常
{
//这些是我们的输入和输出文件的路径
路径输入=Path.get(“input.dat”);
路径输出=Path.get(“output.dat”);
//我们需要以YYYYDDMM格式获取今天的日期,因此我们创建一个
//如果你的日期格式是
//实际上,YYYYMMDD可以只使用DateFormatter.BASIC\u ISO\u DATE
//相反。
DateTimeFormatter formatter=模式的DateTimeFormatter.of(“yyyyddMM”);
字符串todaysDate=LocalDate.now().format(格式化程序);
//使用try with resources创建读写器
try(BufferedReader=Files.newBufferedReader(输入);
BufferedWriter writer=Files.newBufferedWriter(输出)){
弦线;
//读几行,直到没有更多的行
而((line=reader.readLine())!=null){
//在|字符上拆分,注意需要
//已转义,因为它是正则表达式元字符
String[]columns=line.split(“\\\\”);
//迭代每一列。。。
for(int i=0;i return day>=1&&day=1&&month始终是第7列?如果是这样的话,words[6]
就是它所在的位置。不需要正则表达式(而且您没有正确使用它们)请在fileESPYTR\u Big\u file\u EXEC.dat
中发布一个单行的示例。它是纯文本文件吗?Windows上文本文件的常规后缀是.txt
,而不是。dat
后一个后缀通常用于二进制数据文件。@SeanBright-是的,它总是第7列。你能在这里帮我一下吗,你是怎么写的e阅读单词[6]并比较然后更改?yyyydmm
对于日期格式(2018年6月3日为20180306)来说是非常不寻常的。请再次检查是否应该是YYYYMMDD
(2018年3月6日为20180306),这是标准的。第3条记录的第7列不是日期,所以它不能总是第7列。你读了整个问题了吗?你理解问题了吗?你看到这句话了吗:我不能硬编码要搜索的值。这句话:日期格式是固定的YYYYDDMM,日期可以是任何东西我理解这个问题。字符串部分“20180603”应该参数化。如果我没有充分解释,我很抱歉。这就像是charm,这正是我想要的。谢谢你的帮助!基本上回答得很好,谢谢。我认为在这里使用ZonedDateTime
没有任何意义。LocalDate
不是更合适吗?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateReplacer
{
private static final Pattern DATE_MATCHER =
Pattern.compile("(?:(?:19|20)[0-9]{2})([0-9]{2})([0-9]{2})");
public static void main(String... args)
throws Exception
{
// These are the paths to our input and output files
Path input = Paths.get("input.dat");
Path output = Paths.get("output.dat");
// We need to get today's date in YYYYDDMM format, so we create a
// DateFormatter for that. If it turns out that your date format is
// actually YYYYMMDD, you can just use DateFormatter.BASIC_ISO_DATE
// instead.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyddMM");
String todaysDate = LocalDate.now().format(formatter);
// Use try-with-resources to create a reader & writer
try (BufferedReader reader = Files.newBufferedReader(input);
BufferedWriter writer = Files.newBufferedWriter(output)) {
String line;
// Read lines until there are no more lines
while ((line = reader.readLine()) != null) {
// Split them on the | character, notice that it needs to be
// escaped because it is a regex metacharacter
String[] columns = line.split("\\|");
// Iterate over every column...
for (int i = 0; i < columns.length; i++) {
// ... and if the value looks like a date ...
if (isDateLike(columns[i])) {
// ... overwrite with today's date.
columns[i] = todaysDate;
}
}
// Re-join the columns with the | character and write it out
writer.write(String.join("|", columns));
writer.newLine();
}
}
}
private static boolean isDateLike(String str)
{
// Avoid the regular expression if we can
if (str.length() != 8) {
return false;
}
Matcher matcher = DATE_MATCHER.matcher(str);
if (matcher.matches()) {
// If it turns out that your date format is actually YYYYMMDD
// you will need to swap these two lines.
int day = Integer.parseInt(matcher.group(1), 10);
int month = Integer.parseInt(matcher.group(2), 10);
// We don't need to validate year because we already know
// it is between 1900 and 2099 inclusive
return day >= 1 && day <= 31 && month >= 1 && month <= 12;
}
return false;
}
}