我需要替換我的文本文件中的特定行號。我寫了代碼,它正在工作,但有時我的代碼會替換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行。
穿上它,而不是無條件地將所有的線條和使用'input.replace()',爲什麼不加條件,除了當計數線== 1 ?我很確定你的錯誤是,你正在替換數字'tlast'的所有實例數字'最後' – Gus
我在帖子中添加更多信息 – seti