Java 如何获取文件中的特定字符串

Java 如何获取文件中的特定字符串,java,Java,在我的文件内容2017-05-05 08:24:46至2017-05-05 08:24:55中,现在我需要打印日期之间从-2017-05-05 08:24:49至-2017-05-05 08:24:52的内容。除此之外,你能推荐其他方法吗 1.文件内容: [2017-05-05 08:24:46]contents is [ [pool-80 thread.PaseInterceptorChain... zhjkhzjh]nkshxkjghsjkgjskgxsjgxjsagxhujgsxhjs

在我的文件内容2017-05-05 08:24:46至2017-05-05 08:24:55中,现在我需要打印日期之间从-2017-05-05 08:24:49至-2017-05-05 08:24:52的内容。除此之外,你能推荐其他方法吗

1.文件内容:

[2017-05-05 08:24:46]contents is [ [pool-80 
 thread.PaseInterceptorChain... zhjkhzjh]nkshxkjghsjkgjskgxsjgxjsagxhujgsxhjsxghjvasxhasvxhjvsaxhvshjxvhjvhxjvhsvxhj
[2017-05-05 08:24:49]contents is [ [pool-80-thread-1] xhggajgzjh
 icationExceptionOutInterceptor... nvsjhkslkxlxskl]jsahxjahx
[2017-05-05 08:24:49]contents is [ [pool-78-thread-1.. ]
[2017-05-05 08:24:52]contents is [ [pool-78-thread-1... ]
[2017-05-05 08:24:52]contents is [ [pool-78-thread-1... {... = 
 contents inside}]
[2017-05-05 08:24:55]contents is [ [pool-78-thread-1... {... = 
 contents inside}]
2.这是我的代码:

public class MeteringlogBean implements Serializable 
{
private static final long serialVersionUID = 1L;
private Date date10;
private Date date11;
private String d;
private String d1;
private String s;
private String text;
private FileWriter fw;
private BufferedWriter bw;
private String Fn = "C:/Users/swetha.papireddy/Documents/new/filename.txt";
public Date getDate11() {
return date11;
}
public void setDate11(Date date11) {
this.date11 = date11;
}
private String environment;
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
public Date getDate10() {
return date10;
}
public void setDate10(Date date10) {
this.date10 = date10;
}

public void save() throws IOException, NullPointerException {
try {
    File file = new File(getEnvironment() + "/ischange.log");
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
        stringBuilder.append("\n");
    }
    fileReader.close();
    System.out.println("Contents of file:");
    s = stringBuilder.toString();
    System.out.println(s);
} catch (IOException e) {
    e.printStackTrace();
}

d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date10);
System.out.println("date:-" + d);
d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date11);
System.out.println("date:-" + d1);

fw = new FileWriter(Fn);
bw = new BufferedWriter(fw);
bw.write(s);
bw.close();

File file = new File(Fn);
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fis.read(bytes);
fis.close();

String text = new String(bytes, "UTF-8");
String str1 = new String(d);
String str2 = new String(d1);
System.out.println(text.substring(text.indexOf(str1),
        text.lastIndexOf(str2)));
}
3.我的实际产出是:

 [2017-05-05 08:24:49]contents is [ [pool-80-thread-1] xhggajgzjh
icationExceptionOutInterceptor... nvsjhkslkxlxskl]jsahxjahx
[2017-05-05 08:24:49]contents is [ [pool-78-thread-1.. ]
[2017-05-05 08:24:52]contents is [ [pool-78-thread-1... ]
现在我需要两个[2017-05-05 08:24:52]

4.产出应为:

[2017-05-05 08:24:49]contents is [ [pool-80-thread-1] xhggajgzjh
icationExceptionOutInterceptor... nvsjhkslkxlxskl]jsahxjahx
[2017-05-05 08:24:49]contents is [ [pool-78-thread-1.. ]
[2017-05-05 08:24:52]contents is [ [pool-78-thread-1... ]
[2017-05-05 08:24:52]contents is [ [pool-78-thread-1... {... = 
 contents inside}]

您可以使用String.contains(您的搜索字符串)或String.endsWith()或String.startsWith() 或者使用类似的逻辑

while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Do task
         passedLine = true;
    }
    if(passedLine)
    {
       //Do other task after passing the line.
    }
    lineNumber++;
}

您可以使用String.contains(您的搜索字符串)或String.endsWith()或String.startsWith() 或者使用类似的逻辑

while((currentLine = scanner.readLine()) != null)
{
    if(currentLine.indexOf("Your String"))
    {
         //Do task
         passedLine = true;
    }
    if(passedLine)
    {
       //Do other task after passing the line.
    }
    lineNumber++;
}

尝试添加逻辑以获取下一个datetime值,并使用它获取上一个值

例如: 目前,您将获得截至[2017-05-05 08:24:52]的日志。在指定此字符串的最后一个索引之前,请尝试标识“[2017-05-05 08:24:52]”之后的下一个立即日期时间值。 使用String.contains获取它

登录以获取最后一行:

Current datetime = "2017-05-05 08:24:52";
boolean nextValueFound;
while(!nextValueFound){
Date newDate = calender.add(Date, 1); // this will add seconds (not exactly. please check)
//convert the date to String
dateStringtobeCheckedinText = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date11);
if(text.contains(dateStringtobeCheckedinText)){
    nextValueFound = true;
}
}

// your required text:
System.out.println(text.substring(text.indexOf(str1),
        text.indexOf(dateStringtobeCheckedinText )));

尝试添加逻辑以获取下一个datetime值,并使用它获取上一个值

例如: 目前,您将获得截至[2017-05-05 08:24:52]的日志。在指定此字符串的最后一个索引之前,请尝试标识“[2017-05-05 08:24:52]”之后的下一个立即日期时间值。 使用String.contains获取它

登录以获取最后一行:

Current datetime = "2017-05-05 08:24:52";
boolean nextValueFound;
while(!nextValueFound){
Date newDate = calender.add(Date, 1); // this will add seconds (not exactly. please check)
//convert the date to String
dateStringtobeCheckedinText = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date11);
if(text.contains(dateStringtobeCheckedinText)){
    nextValueFound = true;
}
}

// your required text:
System.out.println(text.substring(text.indexOf(str1),
        text.indexOf(dateStringtobeCheckedinText )));

读取文件并将结果存储在字符串生成器中

public static String getInputString(String filepath)  throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile
                (filepath, "r");
        FileChannel channel = randomAccessFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);      //Reading the file in chunk of 1024 bytes[1KB]
        StringBuilder sb = new StringBuilder("");
        while(channel.read(buffer) > 0)
        {
            buffer.flip();                                  //Ready for get ,put operation
            for (int i = 0; i < buffer.limit(); i++)
            {
                sb.append((char)buffer.get());              //Reading every character and appending to Stringbuilder            
            }
            buffer.clear();
        }        
        channel.close();
        randomAccessFile.close();
        return sb.toString(); 
    }
公共静态字符串getInputString(字符串文件路径)引发IOException{
RandomAccessFile RandomAccessFile=新的RandomAccessFile
(文件路径,“r”);
FileChannel=randomAccessFile.getChannel();
ByteBuffer buffer=ByteBuffer.allocate(1024);//读取1024字节块[1KB]中的文件
StringBuilder sb=新的StringBuilder(“”);
而(通道读取(缓冲区)>0)
{
buffer.flip();//准备好获取、放置操作
对于(int i=0;i
使用正则表达式查找日期之间的日志文本:

private  HashMap<String, List<String>> parsedMap = new HashMap<String, List<String>>();
public  HashMap<String, List<String>> getValues(String inputSTring) {
        String regex = "(?=((("Start Date")(.*?|\n.*?)("End Date"))))";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(inputSTring);

        while(matcher.find()) {
            String key = matcher.group(3);
            String value = matcher.group(4);            

            System.out.println(key + " => " + value);
            List<String>contentsList = parsedMap.get(key);
            if(contentsList == null) {
                contentsList = new ArrayList<String>();
                parsedMap.put(key, contentsList);
            }
            contentsList.add(value);
        }
        return parsedMap;       
    }
private HashMap parsedMap=new HashMap();
公共HashMap getValues(字符串inputSTring){
字符串regex=“(?=((“开始日期”)(.*?\n.*?(“结束日期”))”;
Pattern=Pattern.compile(regex);
Matcher Matcher=pattern.Matcher(inputSTring);
while(matcher.find()){
字符串键=matcher.group(3);
字符串值=matcher.group(4);
System.out.println(键+“=>”+值);
ListcontentsList=parsedMap.get(key);
if(contentsList==null){
contentsList=newarraylist();
parsedMap.put(key,contentsList);
}
contentsList.add(value);
}
返回解析的dmap;
}

然后从HashmMap获取值并创建新的输出字符串。

读取文件并将结果存储在字符串生成器中

public static String getInputString(String filepath)  throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile
                (filepath, "r");
        FileChannel channel = randomAccessFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);      //Reading the file in chunk of 1024 bytes[1KB]
        StringBuilder sb = new StringBuilder("");
        while(channel.read(buffer) > 0)
        {
            buffer.flip();                                  //Ready for get ,put operation
            for (int i = 0; i < buffer.limit(); i++)
            {
                sb.append((char)buffer.get());              //Reading every character and appending to Stringbuilder            
            }
            buffer.clear();
        }        
        channel.close();
        randomAccessFile.close();
        return sb.toString(); 
    }
公共静态字符串getInputString(字符串文件路径)引发IOException{
RandomAccessFile RandomAccessFile=新的RandomAccessFile
(文件路径,“r”);
FileChannel=randomAccessFile.getChannel();
ByteBuffer buffer=ByteBuffer.allocate(1024);//读取1024字节块[1KB]中的文件
StringBuilder sb=新的StringBuilder(“”);
而(通道读取(缓冲区)>0)
{
buffer.flip();//准备好获取、放置操作
对于(int i=0;i
使用正则表达式查找日期之间的日志文本:

private  HashMap<String, List<String>> parsedMap = new HashMap<String, List<String>>();
public  HashMap<String, List<String>> getValues(String inputSTring) {
        String regex = "(?=((("Start Date")(.*?|\n.*?)("End Date"))))";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(inputSTring);

        while(matcher.find()) {
            String key = matcher.group(3);
            String value = matcher.group(4);            

            System.out.println(key + " => " + value);
            List<String>contentsList = parsedMap.get(key);
            if(contentsList == null) {
                contentsList = new ArrayList<String>();
                parsedMap.put(key, contentsList);
            }
            contentsList.add(value);
        }
        return parsedMap;       
    }
private HashMap parsedMap=new HashMap();
公共HashMap getValues(字符串inputSTring){
字符串regex=“(?=((“开始日期”)(.*?\n.*?(“结束日期”))”;
Pattern=Pattern.compile(regex);
Matcher Matcher=pattern.Matcher(inputSTring);
while(matcher.find()){
字符串键=matcher.group(3);
字符串值=matcher.group(4);
System.out.println(键+“=>”+值);
ListcontentsList=parsedMap.get(key);
if(contentsList==null){
contentsList=newarraylist();
parsedMap.put(key,contentsList);
}
contentsList.add(value);
}
返回解析的dmap;
}

然后从HashmMap获取值并创建新的输出字符串。

请正确格式化示例代码并使用有意义的变量名。事实上,此代码太难阅读。有两个布尔值表示如果找到第一个字符串,则第二个字符串
如果firsStringFound&&secondStringFound&&dateString不等于secondString,则请断开
请正确格式化示例代码并使用有意义的变量名。事实上,这段代码太难读了。有两个布尔值,表示如果找到第一个字符串,第二个字符串
如果firsStringFound&&secondStringFound&&dateString不等于secondString,则断开
,但这里我没有给出具体的当前日期时间,我可以选择任何日期。date10表示从日期,date11表示到日期。您需要搜索date10的开始到date11行的结束。由于您试图获取is as子字符串,所以需要在第一个字符串和第二个字符串之间进行搜索