简体   繁体   English

从具有条件的文本文件中读取

[英]Read from text file with a condition

I'm reading from a text file with a condition that words starting with * are to be ignored. 我正在读取一个文本文件,其条件是以*开头的单词将被忽略。

example:
abc 1234 *text to be ignored

So in this example, I will ignore "text to be ignored" when reading from text file and will only store abc and 1234 in string array. 所以在这个例子中,当从文本文件中读取时,我将忽略“要忽略的文本”,并且只将字节数组中的abc和1234存储起来。

For this, I have written below code. 为此,我写了下面的代码。 How can I achieve the condition to ignore words starting with * ? 如何实现忽略以*开头的单词的条件?

public static void read(String filename) {
        BufferedReader reader = null;

        try {
            String line;
            reader = new BufferedReader (new FileReader(filename));
            while ((line = reader.readLine()) != null) {
                String[] functionName = line.split("\\s+");         
                            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    }

startWith(String literal) returns true if your String start with the given string literal. 如果String以给定的字符串文字开头,则startWith(String literal)返回true。

For Example : 例如 :

"1234".startsWith("12"); returns true . 返回true

So you should read all the words and check if it starts or even contains *, if so, then ignore the whole word. 因此,您应该阅读所有单词并检查它是否开始甚至包含*,如果是,则忽略整个单词。

Example : 示例:

if(! word.startsWith("*")) {
// add to what ever you want
}

or 要么

if(! word.contains("*")) {
// add to what ever you want
}

You can try indexOf() with substring() like 您可以尝试使用substring()类的indexOf()

 while ((line = reader.readLine()) != null) {
    if(line.indexOf("*")>-1)
    line=line.substring(0,line.indexOf("*"));
    String[] functionName = line.split("\\s+");  
 }

what the above indexOf("*") will give you the index of * then you can just find the substring with with endIndex as the index of * you found by indexOf("*") by doing substring(beginIndex,endIndex) 上面的indexOf("*")会给你*的索引然后你可以通过执行substring(beginIndex,endIndex)找到带有endIndex的子字符串作为indexOf("*")找到的*的索引

You can do something like in your while loop - 你可以在你的while循环中做一些事情 -

while ((line = reader.readLine()) != null) {
   String[] functionName = line.split("\\s+");         
   String newLine = "";

   for(String strg : functionName){

      if(strg.startsWith("*")){
         break;
      }else{
         newLine = strg + newLine;
      }

   }
}

You don't tell what version of Java you are using so I'm going to assume Java 8... 你不知道你正在使用什么版本的Java,所以我将假设Java 8 ......

NOTE: code is untested but it should work with some adaptations. 注意:代码未经测试,但它应该适用于一些调整。

private static final Pattern SPACES = Pattern.compile("\\s+");
private static final Pattern STAR_TO_END = Pattern.compile("\\s*\\*.*");
public static String[] read(final String filename)
{
    final Path path = Paths.get(filename);

    try (
        // UTF-8 by default; excellent
        final Stream<String> lines = Files.line(path);
    ) {
        return lines.map(line -> STAR_TO_END.matcher(line).replaceFirst(""))
            .flatMap(SPACES::splitAsStream)
            .collect(Collectors.toArray(String[]::new));
    }
}

If you dont want to loop through your words to check if it starts with a * you could also remove all the words with asterisks in from of them prior to using split . 如果你不想循环翻阅你的单词以检查它是否以*开头,你也可以在使用split之前删除所有带星号的单词。

String str = "abc 1234 *text to be ignored";
System.out.println(Arrays.toString(str.replaceAll("\\*[^\\s]+\\s*", "").split("\\s+")));
// [abc, 1234, to, be, ignored]
str = "*abc *1234 *text to be *ignored";
System.out.println(Arrays.toString(str.replaceAll("\\*[^\\s]+\\s*", "").split("\\s+")));
// [to, be]

Regex breakdown 正则表达式崩溃

\\* - Literal match of asterisk
[^\\s]+ - Match anything but a space
\\s* - Capture any or no spaces at end of word

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

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