简体   繁体   English

读写文本文件

[英]Read and Write Text File

Would like to know is there any method to read specific data from a text file? 想知道是否有任何方法可以从文本文件中读取特定数据? For example: 例如:

[January 1, 2014 3:57 AM] (EmailDeliveryOptionsHome.getAddEmailDeliveryOptions [Connection at : MayConnectionPool]) : Exception Encountered | [2014年1月1日上午3:57](EmailDeliveryOptionsHome.getAddEmailDeliveryOptions [Connection at:MayConnectionPool]):遭遇异常 (java.sql.SQLException: ORA-12899: value too large for column "BGADMIN"."TBLSTOPRINT_ACCT"."EMAIL_ADDR" (java.sql.SQLException:ORA-12899:值太大而不适用于列“BGADMIN”。“TBLSTOPRINT_ACCT”。“EMAIL_ADDR”

I would like to read the part where they says 我想阅读他们所说的部分

EmailDeliveryOptionsHome.getAddEmailDeliveryOptions EmailDeliveryOptionsHome.getAddEmailDeliveryOptions

but not the rest,I don't really know how to write program to not read the date and [ Connection at: ...... EMAIL_ADDR. 但不是其余的,我真的不知道怎么写程序不读日期和[Connection at:...... EMAIL_ADDR。 Do I need to use buffered reader? 我需要使用缓冲读卡器吗? Or can I use other method as well? 或者我也可以使用其他方法吗?

public static void main(String[] args) {

        try
        {   File myFile = new File("system.txt");
            FileReader filereader= new FileReader(myFile);
            int len=(int)myFile.length();            
            char [] chars = new char[len];
            filereader.read(chars);
            for(int i=0; i<len; i++){
                System.out.print(chars[i]);
            filereader.close();
        }
        }

        catch(IOException e)
        {    System.out.print("Error performing file reading");
        }

this code reads everything, in the text file, how do I modify the text file so that it read only specific data? 此代码读取文本文件中的所有内容,如何修改文本文件以使其只读取特定数据?

You could take a look at the Pattern Class since what you are reading seems to be in some defined format (pattern) and you are always looking for something in particular which can be extracted. 您可以查看Pattern类,因为您正在阅读的内容似乎是某种定义的格式(模式),并且您总是在寻找可以提取的特定内容。

This simple code below should do what you are after: 下面这个简单的代码应该做你想做的事情:

        String input = "[January 1, 2014 3:57 AM] (EmailDeliveryOptionsHome.getAddEmailDeliveryOptions [Connection at : MayConnectionPool]) : Exception Encountered | (java.sql.SQLException: ORA-12899: value too large for column \"BGADMIN\".\"TBLSTOPRINT_ACCT\".\"EMAIL_ADDR\"";
    Pattern p = Pattern.compile("\\[Connection at\\s*:\\s*([^\\]]+)");
    Matcher m  =p.matcher(input);
    if(m.find())
    {
        System.out.println(m.group(1));
    }

This yields: 这会产生:

MayConnectionPool

A simple explanation of this regex can be found here . 这里可以找到这个正则表达式的简单解释。

What this does is as follows: 这样做的内容如下:

  • The [ character is a special character in regex language, and thus must be escaped with an extra \\ in front. [字符是正则表达式语言中的特殊字符,因此必须在前面使用额外的\\来进行转义。 As usual, an extra \\ is needed to escape it for Java. 像往常一样,需要一个额外的\\来逃避Java。
  • Connection at will match exactly those characters Connection at将完全匹配这些字符
  • \\s* will match 0 or more occurrences of a white space character ( \\\\s ) \\ s *将匹配0个或更多出现的空格字符( \\\\s
  • : will match exactly that :将完全匹配
  • \\s* will match 0 or more occurrences of a white space character ( \\\\s ) \\ s *将匹配0个或更多出现的空格字符( \\\\s
  • ([^\\\\]]+) : In regular expression language, the round brackets ( ( and ) respectively) denote a group capture. ([^\\\\]]+) :在正则表达式语言中,圆括号(分别为() )表示组捕获。 Anything which is between these brackets and is matched will be captures and made available later to access. 这些括号之间的任何匹配都将被捕获并在以后访问时可用。 These are needed when you want to extract , not just match information within a given string. 当您想要提取时 ,需要这些,而不仅仅是匹配给定字符串中的信息。 The [] in regex denote a set of characters which you would like to match, so [abc] will match a , b and c , in no particular order. 正则表达式中的[]表示您想要匹配的一组字符,因此[abc]将匹配abc ,没有特定的顺序。 However, if you have characters which follow the ^ character, then, the effect is opposite meaning that it will match anything which is not within the square brackets. 但是,如果你有跟随^字符的字符,那么效果相反意味着它将匹配不在方括号内的任何东西。 So in short, what [^\\\\]]+ is that it will match 1 or more repetitions of ( + ) any character which is not a closing square bracket ( \\\\] ). 所以简而言之, [^\\\\]]+是否会匹配( + )任何不是结束方括号( \\\\] )的字符的1次或多次重复。 Anything which matches will be placed in a group which I am later accessing. 匹配的任何内容都将放在我稍后访问的组中。

This is a quick but a bit dirty way that I use: 这是我使用的快速但有点脏的方式:

Use this (or use your own method) to get the file content: 使用此(或使用您自己的方法)来获取文件内容:

Scanner s = new Scanner(new File("textfile.txt"));
String fileContent = "";
if(s.hasNextLine()) { // If multiline
    while(s.hasNext()) {
        fileContent += s.nextLine() + "\n";
    }
}else { // If only one line
    while(s.hasNext()) {
        fileContent += " " + s.next();
    }
    // Remove the first space
    fileContent = fileContent.trim();
}

To strip the data you wanted out of the file use: 要从文件中删除您想要的数据,请使用:

String result = null;
String searchFor = "EmailDeliveryOptionsHome.getAddEmailDeliveryOptions";
if(fileContent.contains(searchFor)) {
result = fileContent.substring(
                fileContent.indexOf(searchFor), 
                fileContent.indexOf(searchFor) + searchFor.length());
}

Now you have the result in a variable called result or if it wasn't found result is null. 现在,您将结果存储在名为result的变量中,或者如果未找到,则result为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM