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();
}
}