簡體   English   中英

在txt文件中查找特定文本並將其存儲在String中

[英]Finding specific text in txt file and storing it in String

首先,我想說我是初學者,這是我的第一個Java程序。 我想創建一個程序來讀取文本文件,找到特定的行,並將其保存到我的字符串變量中。

所以我想找到以“Dealt to”開頭的行,然后在那行中復制所有內容,直到這個char'['並將它放在我的字符串變量中。

所以我要說我在我的文本文件中有這一行: Dealt to My NickName [text]我想要一個程序找到文本“我的昵稱”並將它放在我的字符串變量中。

我正在嘗試使用類並嘗試使用setter和getter來練習,請讓我知道我的代碼是什么樣的,以及如何改進它並讓它工作。

這是Main.java:

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException{
        HandHistory hh1 = new HandHistory();
        String hero1 = null;

        hero1 = hh1.getHero();
        System.out.println(hero1);

    }
}

我的HandHistory.java:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class HandHistory {

    private String hero; 

    public HandHistory(){}

    public String getHero() throws IOException {
        FileReader in = new FileReader("G:/Java/workspace/HandHistory/src/File.txt");
        BufferedReader br = new BufferedReader(in);

        String line;
        while ((line = br.readLine()) != null) {
            if (line.contains("Dealt to ")){
                hero = line.substring(9,(line.indexOf("["))-1);

            }
        }                   
        return hero;
    }

    public void setHero(String hero){
        this.hero = hero;
    }
}

這是一個良好的開端,是逐行讀取文件的好方法。 值得修復的一個問題是使用try-finally塊關閉FileReader資源,或者從Java 7開始使用新的try-with-resources塊:

try (FileReader in = new FileReader("G:/Java/workspace/HandHistory/src/File.txt")) {
  ...
}

我能想到的其他提示和評論:

  • 如果你實際上不需要它,你不必在你的班級里有一個二傳手
  • 如果有行包含字符串“Dealt to”但不以該字符串開頭,則代碼不起作用。 例如,“Foobar Dealt to My NickName [text]”仍將匹配,但會返回錯誤的值
  • 如果你真的只想匹配以“Dealt to”開頭的行,那么使用String.startsWith()而不是String.contains()
  • 當字符串中沒有“[”時,您應該處理這種情況,否則您的代碼會因難以理解的錯誤而崩潰
  • 如果正則表達式從代碼中刪除復雜性,則它們很有用。 在你的情況下,問題可以通過相對容易地使用startsWith和indexOf來解決,所以在這種情況下我不會使用RegExps
  • 沒有查看實際代碼,HandHistory.getHero()的作用並不明顯。 即使你自己為表達類或方法實際上做什么的事物分配名稱,它總是非常有用。
  • 可以說getHero()方法做了太多事情,HandHistory類也做了太多事情,但是當使用代碼比學習hello-world示例更大的東西時,這可能需要考慮。

我的建議是使用正則表達式。 你可以試試

(?<=beginningstringname)(.*\n?)(?=endstringname)

所以,對於你的問題,這將是

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

      // String to be scanned to find the pattern.
      String line = "Dealt to My NickName [text]";
      String pattern = "(?<=Dealt to )(.*\n?)(?=[)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);

      //m now haves what you desire. You can loop it if you want.
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}

嘗試使用本教程在Java http://www.tutorialspoint.com/java/java_regular_expressions.htm中使用正則表達式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM