2011-07-13 9 views
0

私は別のファイルをコピーしましたが、次のコードを使用して2番目のファイルに同じテキストが含まれているので、私のファイル(特に2行目)から行を削除します。私の最終的なファイルの.xml)ファイルの位置を知ってファイルから行を削除するには?

public static File fileparse() throws SQLException, FileNotFoundException, IOException { 
    File f=fillfile();//my original file 
    dostemp = new DataOutputStream(new FileOutputStream(filetemp)); 
    int lineremove=1; 
    while (f.length()!=0) { 
     if (lineremove<2) { 
      read = in.readLine(); 
      dostemp.writeBytes(read);  
      lineremove++; 
     } 

     if (lineremove==2) { 
      lineremove++; 
     } 

     if (lineremove>2) { 
      read = in.readLine(); 
      dostemp.writeBytes(read); 
     } 
    } 

    return filetemp; 
} 
+1

2番目の後に何が起こるかを考えてください。それは本当にあなたが望むものですか? – Jacob

答えて

5

lineremoveは2ともされている場合は、行を読んでいませんあなたが2だったときにそれを増やした後に2より大きいかどうかをチェックします。これは次のようになります:

int line = 1; 
String read = null; 
while((read = in.readLine()) != null){ 
    if(line!=2) 
    { 
    dostemp.writeBytes(read);  
    } 
    line++; 
} 
2

あなたは、行ずつ読んで、それならば、あなたがしたい行をチェックして、あなたはいけないラインをスキップするreadLine()方法でBufferedReaderを使用することができます。

でドキュメントを確認してください:ここBufferedReader

は、実施例(未最も美しいまたはクリーン:))です:

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    BufferedReader in = null; 
    try { 
     in = new BufferedReader(new FileReader("d:\\test.txt")); 
    } catch (FileNotFoundException e3) { 
     // TODO Auto-generated catch block 
     e3.printStackTrace(); 
    } 
    PrintWriter out = null ; 
    try { 
     out = new PrintWriter (new FileWriter ("d:\\test_out.txt")); 
    } catch (IOException e2) { 
     // TODO Auto-generated catch block 
     e2.printStackTrace(); 
    } 

    String line = null; 
    int lineNum = 0; 
    try { 
     while((line = in.readLine()) != null) { 
      lineNum +=1; 
      if(lineNum == 2){ 
       continue; 
      } 
      out.println(line); 
     } 
    } catch (IOException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    out.flush(); 

    out.close(); 
    try { 
     in.close(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 
関連する問題