簡體   English   中英

如何讀取文件並尋找到另一行的特定行-Java

[英]How To Read A File and Look For a Specific Line to Another Line - Java

因此,我想讀取一個文件並查找特定的行,然后查找50行左右,然后從該文件中刪除這些行,並將其他行寫入另一個文件。 我需要一些入門幫助,以及一些方法的想法。 我打算做一個簡單的方法。 例如,這將是txt文件:

hi
hey
12
14
456
234
23
bye
53
2312
434

我想找到“嘿”行,並從“嘿”刪除所有行,直到“再見”(包括)。 並在文件中的不同位置重復多次(大約1000次)。 另外,它們之間的行數將始終相同...因此,如果可能的話,我什至可以從“嘿”和下一個____行數中刪除。 感謝您的任何想法!

FileInputStream fstream = new FileInputStream("file name");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine; 

//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
}

//Close the input stream
br.close();
}

這應該可行,它將兩個單詞用作程序參數(例如MyApp.jar hey bye

public class Main
{
     public static void main(String[] args)
     {
         if(args.length < 2) 
         {
             System.exit(0);
         }
         String ignoreStartWord = args[0];
         String ignoreEndWord = args[1];
         BufferedReader br = null;
         BufferedWriter bw = null;
         try
         {
             br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("fileName"))));
             bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("fileName2"))));
             boolean ignoreStarted = false;
             String line = null;
             while((line = br.readLine()) != null)
             {
                 if(ignoreStarted == false)
                 {
                     if(line.equals(ignoreStartWord))
                     {
                         ignoreStarted = true;
                     }
                     else
                     {
                         bw.write(line);
                         bw.newLine();
                     }
                 }
                 else
                 {
                     if(line.equals(ignoreEndWord))
                     {
                         ignoreStarted = false;
                     }
                 }
            }
        }
        catch(IOException e)
        {
             e.printStackTrace();
        }
        catch(FileNotFoundException e)
        {
             e.printStackTrace();
        }
        finally
        {
             if(br != null) try { br.close(); } catch(IOException e) {}
             if(bw != null) try { bw.close(); } catch(IOException e) {}
        }
    }
}

輸入:

hi
hey
12
14
456
234
23
bye
53
2312
434
hi
hey
12
14
456
234
23
bye
53
2312
434
hi
hey
12
14
456
234
23
bye
53
2312
434
hi
hey
12
14
456
234
23
bye
53
2312
434

輸出:

hi
53
2312
434
hi
53
2312
434
hi
53
2312
434
hi
53
2312
434

暫無
暫無

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

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