【发布时间】:2014-07-22 22:16:10
【问题描述】:
我需要替换文本文件中的特定行号。我编写了代码并且它正在工作,但有时我的代码替换了 2 行。什么是坏的?有没有更快的方法来替换不使用我的方法? 好的,这是代码
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();
我使用了这个功能 2 次。第一行从数据库保存最后一个 ID,第二行从另一个数据库保存最后一个 ID。我需要将此 ID 用于最后更改的数据库行。
【问题讨论】:
-
而不是无条件地添加所有行并使用
input.replace(),为什么不有条件地添加行,除非count==1?我很确定您的错误是您将数字tlast的所有实例替换为数字last -
我在帖子中添加更多信息