2014-07-22 38 views
0

我需要替換我的文本文件中的特定行號。我寫了代碼,它正在工作,但有時我的代碼會替換2行。什麼是壞的?有更快的方法來取代不使用我的方法? 確定這是代碼我使用此功能2倍使用java替換文本文件中的行號

int last=0; 
Boolean brak=false; 
try{ 

    BufferedReader br = new BufferedReader(new FileReader("last.txt")); 
String strLine; 
int count=0; 
//Read File Line By Line 
while ((strLine = br.readLine()) != null) { 
    // Print the content on the console 
    if(count==1) {last=Integer.parseInt(strLine); 


    } 
    count++; 
} 
//Close the input stream 
br.close(); 
}catch (FileNotFoundException e){//Catch exception if any 
     System.out.println(e.toString()); 
     brak=true; 
    } 
catch (IOException e) { 
     e.printStackTrace();} 
try(Connection c = MsSqlConnect.getConnection()) 
{ 
    System.out.println(last); 

    String SQL = "Select ob_id,ob_dokMagId,dok_NrPelny,ob_TowId,tw_Nazwa,ob_IloscMag,ob_WartBrutto,dok_Typ from dok_Pozycja dp " 
+ "RIGHT JOIN dok__Dokument ON dok_Id=ob_DokMagId " 
+ "LEFT JOIN tw__Towar ON tw_Id=ob_TowId " 
+ "Where ob_TowRodzaj=1 AND dp.ob_id>"+last; 
ResultSet rs = c.createStatement().executeQuery(SQL); 
int tlast=last; 
while(rs.next()){ 
    data.add(new OrderSU(rs.getInt("ob_dokMagId"), rs.getString("dok_NrPelny"), rs.getInt("ob_TowId"), rs.getString("tw_Nazwa"), rs.getInt("ob_IloscMag"), rs.getFloat("ob_WartBrutto"),rs.getInt("dok_Typ"))); 
last=rs.getInt("ob_id"); 
    } 
if(brak==true){ 
    try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("last.txt", true)))) { 
out.print("0"+"\r\n"+last); 
}catch (IOException e) { 
    //exception handling left as an exercise for the reader 
    } 
} 
else 
{ 
    try { 
     System.out.println(last+" "+tlast); 
BufferedReader file = new BufferedReader(new FileReader("last.txt")); 
String line;String input = ""; 
    int count=0; 
    while ((line = file.readLine()) != null){ 
     input += line + "\r\n"; 
      if(count==1) { 
       input = input.replace(Integer.toString(tlast), Integer.toString(last)); 
      } 
      count++; 
     } 

     file.close(); 
     System.out.print(input); 
FileOutputStream File = new FileOutputStream("last.txt"); 
    File.write(input.getBytes()); 
    file.close(); 
} catch (Exception e) { 
    System.out.println("Problem reading file."); 
    } 
} 
c.close(); 

。第一行保存來自DB的最後一個ID,第二行保存另一個DB的最後一個ID。我需要把這個ID保存到更改的db行。

+0

穿上它,而不是無條件地將所有的線條和使用'input.replace()',爲什麼不加條件,除了當計數線== 1 ?我很確定你的錯誤是,你正在替換數字'tlast'的所有實例數字'最後' – Gus

+0

我在帖子中添加更多信息 – seti

回答

2

input是累積的。也就是說,如果您從文件中讀取了5行,則input將包含全部5行。所以,如果你說

input = input.replace(Integer.toString(tlast), Integer.toString(last)); 

在這一點上,因爲input包含5行文字,它會執行這些線路的所有5個更換。

如果您只想在一條輸入線上進行替換,則需要修復邏輯。

+0

真正的我不考慮什麼。我認爲我必須採取行或改變需求和添加輸入。我添加了更多信息發佈。當另一個函數不關閉文件時,可能會發生FileNotFoundException異常? – seti

0

您可能想要將最後一行讀入不同的變量。 「輸入」包含迄今爲止所讀的所有內容。

0

試試這個:

line = line.replace(Integer.toString(tlast), Integer.toString(last)); 

input += line + "\r\n";

相關問題