只有最后一行被写入文件

时间:2017-06-16 08:04:41

标签: java printwriter

我需要帮助。我试图将有效的串行密钥与无效的串行密钥分开。我输出正确了。但是当我试图在一个文件中写它时,只写了最后一行。 输出是:

1A000000 1A000001 1A000002 1A000003 1A000004 1A000005 2B200012 3C343455 4D342423 5E324344 6F435435 7G245347

我希望将其写入文件。但是只写了7G245347。

import java.util.*;`
import java.io.*;
public class ValidSerialKey {

    public static void main(String[] args) throws IOException {
        String keys = "";

        File file = new File("serialkeys.txt");
        try{        
        Scanner scan = new Scanner(file);        
            while (scan.hasNext()){
                keys = scan.nextLine();

               if ((keys.charAt(0) == '1' || keys.charAt(0) == '2' || keys.charAt(0) == '3' || keys.charAt(0) == '4' || keys.charAt(0) == '5' || 
                    keys.charAt(0) == '6' || keys.charAt(0) == '7' || keys.charAt(0) == '8' || keys.charAt(0) == '9' ) && 
                   (keys.charAt(1) == 'A' || keys.charAt(1) == 'B' || keys.charAt(1) == 'C' || keys.charAt(1) == 'D' || keys.charAt(1) == 'E' || 
                    keys.charAt(1) == 'F' || keys.charAt(1) == 'G' || keys.charAt(1) == 'H' || keys.charAt(1) == 'I' || keys.charAt(1) == 'J' ||
                    keys.charAt(1) == 'K' || keys.charAt(1) == 'L' || keys.charAt(1) == 'M' || keys.charAt(1) == 'N' || keys.charAt(1) == 'O' ||
                    keys.charAt(1) == 'P' || keys.charAt(1) == 'Q' || keys.charAt(1) == 'R' || keys.charAt(1) == 'S' || keys.charAt(1) == 'T' ||
                    keys.charAt(1) == 'U' || keys.charAt(1) == 'V' || keys.charAt(1) == 'W' || keys.charAt(1) == 'X' || keys.charAt(1) == 'Y' ||
                    keys.charAt(1) == 'Z' )){

                    System.out.println(keys);

                    File filein = new File("ValidKeys.txt");
                    try{
                        try
                           (PrintWriter pw = new PrintWriter(filein)){
                               pw.print(keys);
                               pw.close();
                        }
                    }catch (FileNotFoundException ex){
                      System.out.println(ex.getMessage());
                    }


               }//end of if             
            }//end of while
            scan.close();
        }catch (FileNotFoundException exp){
            System.out.println(exp.getMessage());
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您希望在循环的下一次迭代期间保持PrintWriter打开以写入其他内容 所以不要在每次迭代时创建一个新的。

作为旁注,您在使用PrintWriter时无需明确关闭try with resources实例。

你应该替换这个逻辑:

loop     
    try
       (PrintWriter pw = new PrintWriter(uniqueFile)){
           pw.print(keys);             
    }//end of inner try

end loop

通过逻辑,在try with resources语句中包含整个逻辑:

try(PrintWriter pw = new PrintWriter(uniqueFile)){
    loop  
        pw.print(keys);                       
    end loop
}
catch (IOException e){ 
   ... // exception handling
}