繁体   English   中英

使用Java替换文本文件中的行号

[英]Replace line number in text file using java

我需要在文本文件中替换特定的行号。 我编写了代码,并且可以正常工作,但是有时我的代码替换了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是累积的。 也就是说,如果您从文件中读取了5行,则input将包含所有5行。 所以如果你说

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

此时,由于input包含5行文本,因此它将对所有5行进行替换。

如果您只想在一根输入线上进行替换,则需要修正您的逻辑。

您可能希望将最后一行保留在另一个变量中。 “输入”保留到目前为止已阅读的所有内容。

尝试以下方法:

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

将其放在input += line + "\\r\\n";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM