簡體   English   中英

編輯文本文件中的一行

[英]edit a line in text file

所以我有一個文本文件,包括:

not voting/1/harold/18
not voting/2/isabel/24

這描述了not voting/number for vote/name/age 我的目標是編輯not votingvoted但仍保留其他信息( number for vote/name/age )。 用戶將輸入投票號碼,如果存在,則not voting將自動更改為voted

這是我的代碼:

            File original = new File("C:\\voters.txt");     
            File temporary = new File("C:\\tempvoters.txt");

            BufferedReader infile = new BufferedReader(new FileReader(original));
            PrintWriter outfile = new PrintWriter(new PrintWriter(temporary));

            numberforvote=JOptionPane.showInputDialog("Enter voters number: ");
            String line=null;

            while((line=infile.readLine())!=null){

                String [] info=line.split("/");
                if(info[1].matches(numberforvote)){
                    all="VOTED"+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
                    outfile.println(all);
                    outfile.flush();
                }
            }
        infile.close();
        outfile.close();

        original.delete();
        temporary.renameTo(original);

這工作但我的代碼的問題是第二行( not voting/2/isabel/24 )將消失/刪除。 我希望一切都是一樣的,除非not voting給定/輸入的數字沒有投票。

if(info[1].matches(numberforvote)){
     all="VOTED"+"/"+info[1]+"/"...;
     outfile.println(all);
     outfile.flush();
} else {
     outfile.println( line );
}

如果沒有匹配則復制到輸出。

我應該補充說,使用正則表達式進行單個字符串比較應該簡化為更簡單的info[1].equals(numberforvote) 但是調用numberforvote = numberforvote.trim(); 可能有用。

您的輸出文件被完全覆蓋,因此您必須編寫所有行,即使是那些您不打算修改的行:

      if(info[1].matches(numberforvote)){
            all="VOTED"+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
            outfile.println(all);
       }
      else{
            outfile.println(line); // this will write the "unchanged" lines
       }

        outfile.flush();

將它移到if之外,只更改你需要更改的部分。 這樣你可以改變你想要的任何東西然后重建線。

if(info[1].matches(numberforvote)){
  into[0] = VOTED;
}

all=info[0]+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];

outfile.println(all);
outfile.flush();

或清理那條丑陋的線條

 StringBuilder sb = new StringBuilder();
 for (String element : info){
    sb.append(element);
 }
 outfile.println(sb.toString());

其他答案

您可以像其他人建議的那樣輸出未更改的行

outfile.println(line);

但如果您想稍后進行其他更改,則不具備靈活性。

您應該簡化拆分並寫入:

String [] info=line.split("/",2);
if ( info.length == 2 ) {
   ...
   outfile.println("VOTED/"+info[1]);
} else {
  // input error
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM