简体   繁体   English

我无法弄清楚为什么用数组覆盖文件的内容导致空文件

[英]I can't figure out why overwriting a file's contents with an array results in an empty file

So I fixed the overwriting problem but now the issue is it eats the last line of the text file. 所以我修复了覆盖问题,但现在问题是它吃掉了文本文件的最后一行。 Or I suppose It's just not writing it back to the file. 或者我想它只是没有把它写回文件。 Any ideas? 有任何想法吗? The first method should change the password to a random one and the second one is just for counting the number of lines in the text file. 第一种方法应该将密码更改为随机密码,第二种方法只是用于计算文本文件中的行数。

/**
 *  Method for resetting a password
 * Replaces current password with randomly generated one.
 * 
 *  @param testUserName is the username used for finding the password
 *       to replace
 */
public String resetPassword(String testUserName) throws IOException  {
    int fileLength = countLines();
    FileReader fr = new FileReader("Password.txt");
    BufferedReader br = new BufferedReader(fr);
    String[] storeData = new String[fileLength];
    Random rand = new Random();
    int pwNumber = (int)(rand.nextDouble() * 10000);
    String pwReset = "Password" + pwNumber;

    for (int i=0; i < fileLength; i ++) {
        storeData[i] = br.readLine();
    }
    fr.close();     

    for (int i=0; i < (fileLength-1); i += 4) {
        if (testUserName.equals(storeData[i])) {
            storeData[i+1] = pwReset;
        }   
    }
    PrintWriter reset = new PrintWriter("Password.txt");
    for (int i=0; i < fileLength; i ++) {
        reset.println(storeData[i]);
    }
    reset.close();
    return pwReset;
}

/**
 *  Method for counting number of lines in a file
 *  Used in conjuction with other methods for reading
 * specific lines of files.
 */
public int countLines() throws IOException {
   InputStream is = new BufferedInputStream(new FileInputStream("Password.txt"));
   try {
      byte[] c = new byte[1024];
      int count = 0;
      int readChars = 0;
      boolean empty = true;
      while ((readChars = is.read(c)) != -1) {
         empty = false;
         for (int i = 0; i < readChars; ++i) {
            if (c[i] == '\n')
               ++count;
        }       
      }
      return (count == 0 && !empty) ? 1 : count;
    } finally {
      is.close();
   }
}

I suspect you countLines() method is re-reading the file to determine the number of lines at that moment. 我怀疑你countLines()方法正在重新读取文件以确定那一刻的行数。 This is not only very inefficient, but also the source of your bug. 这不仅非常低效,而且还是您的bug的来源。

PrintWriter reset = new PrintWriter("Password.txt");
// file is now truncated.
countLine() == 0

I suggest you count the number of lines once. 我建议你计算一次的行数。 ideally when you read it once. 理想情况下,当你读一次。


You can improve it by 你可以改进它

  • reading the file once. 一次读取文件。
  • not storing the file in memory so it doesn't matter how big it is. 不将文件存储在内存中,因此它无关紧要。
  • if it fails to write the file, the original is untouched. 如果它无法写入文件,则原始文件不会受到影响。

.

public String resetPassword(String testUserName) throws IOException {
    File passwdFile = new File("Password.txt");
    BufferedReader br = new BufferedReader(new FileReader(passwdFile));
    File tmpPasswdFile = new File("Password.txt.tmp");
    PrintWriter reset = new PrintWriter(tmpPasswdFile);
    String pwReset = null;
    try {
        boolean resetNextLine = false;
        for (String line; (line = br.readLine()) != null; ) {
            if (resetNextLine) {
                Random rand = new Random();
                int pwNumber = (int) (rand.nextDouble() * 10000);
                pwReset = "Password" + pwNumber;
                reset.println(pwReset);
            } else {
                reset.println(line);
            }
            resetNextLine = testUserName.equals(line);
        }
    } finally {
        reset.close();
        br.close();
    }
    passwdFile.delete();
    tmpPasswdFile.renameTo(passwdFile);
    return pwReset;
}

How does countLines() work ? countLines()如何工作?

I'm a bit suspicious of this approach since you're using the result of this to iterate through your array. 我对这种方法有点怀疑,因为你正在使用它的结果迭代你的数组。 I would have thought it was perhaps more intuitive (and correct?) to iterate through the array using its length. 我本以为使用它的长度迭代数组可能更直观(也更正确?)

暂无
暂无

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

相关问题 无法弄清楚为什么我的程序不打印数组内容 - Can't figure out why my program is not printing contents of array 无法弄清楚为什么IO文件的索引超出范围 - Can't figure out why index is out of bound for IO file 我不知道为什么我的代码可以在终端和Eclipse中正确运行,但不能单独作为jar文件运行 - I can't figure out why my code runs correctly in terminal and eclipse, but not as a jar file by itself 骑士巡回赛-导致无限循环,我不知道为什么 - Knights tour - results in an infinite loop and i can't figure out why 从PHP文件接收HTTP POST回显响应(发送POSTS效果很好,这是我不知道的接收信息) - recieving HTTP POST echo response from a PHP file (sending the POSTS works fine, it's the receive that I can't figure out) 我正在使用Servlet,但似乎无法弄清楚为什么我的下载文件Servlet可以在本地运行,但不能正常运行 - I'm using Servlets and can't seem to figure out why my download file servlet will work locally, but not otherwise 我无法弄清楚输入是否为空 - I can't figure out to print if input is empty or not 我不知道为什么我的数组没有填写 Java - I can't figure out why my array isn't filling here in Java 我无法弄清楚我的NullPointerException有什么问题或者为什么它甚至存在 - I can't figure out what's wrong with my NullPointerException or why it even exists 我无法弄清楚比较数组索引有什么问题 - I can't figure out what's wrong with comparing array indexes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM