2011-08-22 49 views
2

我需要幫助僅顯示文件中的文本,該文件以「Hello」開頭並以「Bye」結尾。我可以掃描整個文本文件並進行打印,但我只需要打印出由兩個變量定義的特定範圍。這是我到目前爲止,任何提示將不勝感激。謝謝! :)JAVA從文本文件中掃描並僅顯示兩個關鍵字/變量之間的文本

public static void main(String[] args) { 
    // TODO code application logic here 
    File fileName = new File("hello.txt"); 
    try { 
     Scanner scan = new Scanner(fileName); 
     while (scan.hasNextLine()) { 
      String line = scan.nextLine(); 
      System.out.println(line); 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 
+1

您可以使用狀態變量來存儲您是否在「Hello」/「Bye」對之間。根據您在輸入中找到的內容更改變量。根據你所處的狀態打印行。 – Giorgio

回答

2

該文件有多大?除非它很大,否則將文件作爲一個字符串讀取並剪掉你想要的位。

File file = new File("Hello.txt"); 
FileInputStream fis = new FileInputStream(file); 
byte[] bytes = new byte[(int) file.length()]; 
fis.read(bytes); 
fis.close(); 
String text = new String(bytes, "UTF-8"); 
System.out.println(text.substring(text.indexOf("START"), text.lastIndexOf("END"))); 

使用Apache文件實用程序

String text = FileUtils.readFileToString("hello.txt"); 
System.out.println(text.substring(text.indexOf("START"), text.lastIndexOf("END"))); 
+0

該文件實際上是4000行... – Yan

+0

使用fis工作,謝謝!現在研究如何讓它只顯示一次,因爲它們在整個文本文件中是多個「再見」,並且包含了它們的全部內容。但確實取得了進展,再次感謝! – Yan

+0

你想從第一個Bye(使用indexOf)開始,還是最後一個?你有決定。 –

1

我不知道你是否意味着您好,再見必須是在同一行或跨越多行?試試這個(修改startToken和endToken適合):

public static void main(String[] args) { 
    // TODO code application logic here 
    File fileName = new File("hello.txt"); 
    try { 
     String startToken = "Hello"; 
     String endToken = "Bye"; 
     boolean output = false; 

     Scanner scan = new Scanner(fileName); 
     while (scan.hasNextLine()) { 
      String line = scan.nextLine(); 
      if (!output && line.indexOf(startToken) > -1) { 
       output = true; 
       line = line.substring(line.indexOf(startToken)+startToken.length()); 
      } else if (output && line.indexOf(endToken) > -1) { 
       output = false; 
       System.out.println(line.substring(0, line.indexOf(endToken))); 
      } 

      if (output) { 
       System.out.println(line); 
      } 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 
+0

不只是給作業問題的答案 –

0

可以使用的狀態變量來存儲你是否是一個「你好」 /「再見」對與否之間。根據您在輸入中找到的內容更改變量。根據你所處的狀態打印文本。

我將Java的實現留給你。 :-)

2
public static void main(String[] args) { 
    // TODO code application logic here 
    File fileName = new File("hello.txt"); 
    try { 
     Scanner scan = new Scanner(fileName); 
     while (scan.hasNextLine()) { 
      String line = scan.nextLine(); 
      System.out.println(line); 
      int indexHello = line.lastIndexOf("hello",0); 
      int indexBye = line.indexOf("bye". indexHello); 
      String newString = line.substring(indexHello, indexBye); 


     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
}