所以我有一个程序可以保存你的密码和用户名,然后将它们保存在.txt文件中。 我添加了删除其中一个条目的选项,以防您拼写错误或其他内容。这就是我的文本文件。
Website
Username
Password
anotherWebsite
anotherUsername
anotherPassword
现在密码没有被加密,因为我被指示不加密它们。
我的主要问题是,您是否能够删除文本文件中的某些行而不读取整个文件,然后将所需的行保存到新文件然后使用该文件?
答案 0 :(得分:2)
你的问题的答案是否定的。基本上,执行此操作的方法是重写文件,省略要删除的行
答案 1 :(得分:1)
你需要做的是重写你的整个文件,而不是写你想跳过的行。
Find a line in a file and remove it的一个实现对您的情况来说似乎已经足够了,您只需要检查3件事(元组(网站,用户名,密码)而不是只有一个参数。
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
答案 2 :(得分:1)
如果没有其他临时文件进行读写,我不知道如何做到这一点。 我认为这是不可能的,因为你将它作为字节数组读取并使用一些高级API。
如果您使用的是Java 8,我建议使用此结构:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public static void main(String[] args) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("duke.java")));
}
然后,使用字符串,您可以阅读,连接或删除信息。
链接:http://www.adam-bien.com/roller/abien/entry/java_8_reading_a_file
如果您使用的是其他版本,请点击以下链接:
答案 3 :(得分:1)
在文件中,每个信息位都有一个位置。删除其中一些位不会移动其他元素的位置。
File
1111111111111111
222222222.....22
3333.33333.3.333
44.444.444.444.4
5555555555555555
变为
1111111111111111
222222222.....22
44.444.444.444.4
5555555555555555
删除
3333.33333.3.333
移动
44.444.444.444.4
5555555555555555
进入之前持有的位置
3333.33333.3.333
44.444.444.444.4
所以你可以在没有临时文件的情况下进行,使用以下技术购买
当然这真的非常危险;因为程序中的任何中断都会留下一个不是原始文件的文件,也不会产生结果。由于文件副本很容易被断电,被杀死的程序等中断,你真的不想要这种方法,因为它很难从失败中恢复。
这就是为什么写第二个文件,等到完成后再将其移到原始文件上是一个更好的解决方案。