[英]Is there a way to modify a file and read from the new file, which has the new content?
When I delete a line from a text file, add it to a temporary text file, then replace the temporary file with the original, the scanner isn't loading the correct text. 当我从文本文件中删除一行时,将其添加到临时文本文件,然后用原始文件替换临时文件,扫描仪没有加载正确的文本。 It is loading the content from the original file, not the updated file.
它正在加载原始文件中的内容,而不是更新的文件。 I want it to load the updated file with the new content.
我希望它用新内容加载更新的文件。
try
{
File inputFile = new File("department.txt");
File tempFile = new File("departmentTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = departResIDField.getText();
String currentLine;
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
fWriter = new FileWriter(inputFile.getAbsoluteFile(), true);
printOut = new PrintWriter(fWriter);
writer = new BufferedWriter(fWriter);
writer.write(departResIDField.getText() + "\t" +
departResNameField.getText() + "\r\n");
writer.close();
int result = Integer.parseInt(departResIDField.getText());
depart.add(new Department(result, departResNameField.getText()));
insResDepartModel.addElement(departResNameField.getText());
depart.remove();
//This is where I am having problem with the code
//The scanner is scanning old data not the updated data
Scanner scan = new Scanner(inputFile);
while(scan.hasNext())
{
depart.add(new Department(scan.nextInt(), scan.next()));
}
scan.close();
for(int i = 0; i < depart.getSize(); i++)
{
Department d1 = depart.get(i);
System.out.println(d1.departID + d1.departName);
}
menuLayout.show(cardLayout, "15");
departResIDField.setText(null);
departResNameField.setText(null);
departUpdateButton.setVisible(false);
departCancelButton.setVisible(false);
} catch (IOException f)
{
f.printStackTrace();
}
Output: 1 Biology 2 Chemistry 4 Statistics 5 Physics 3 Math 输出:1生物学2化学4统计学5物理3数学
Expected Output: 1 Biology 2 Chemistry 4 Statistics 5 Physics 3 Calculus 预期产出:1生物学2化学4统计5物理3微积分
Code removes "3 Math" and adds "3 Calculus 代码删除“3 Math”并添加“3微积分
Of course there is a way. 当然有办法。 But I would recommend you to save with something like a
LinkedList
, on an text file if you want only save subjects, and try to read and write only one File
. 但是,如果您只想保存主题,我会建议您在文本文件中保存类似
LinkedList
的内容,并尝试只读取和写入一个File
。 You can save complex data structures with ObjectOutputStream
for example. 例如,您可以使用
ObjectOutputStream
保存复杂的数据结构。 LinkedList
java utility has an instruction named replace
to modify certain index. LinkedList
java实用程序有一个名为replace
的指令来修改某个索引。 So if you want to modify the File
you load the LinkedList
saved then you modify the list and save it in the same file. 因此,如果要修改
File
,则加载已保存的LinkedList
然后修改列表并将其保存在同一文件中。
From my understanding, you want to replace the line containing "3 Math" with "3 Calculus". 根据我的理解,您希望将包含“3 Math”的行替换为“3 Calculus”。 If that's the case you can do something like this:
如果是这种情况,你可以这样做:
Path wiki_path = Paths.get("data/sample.txt");
Charset charset = Charset.forName("UTF-8");
FileInputStream fis = null;
FileOutputStream fos = null;
try {
List<String> lines = Files.readAllLines(wiki_path, charset);
int targetToReplaceIndex = -1;
// You can modify this part to match your logic
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).startsWith("3 Math")) {
targetToReplaceIndex = i;
break;
}
}
lines.set(targetToReplaceIndex, "3 Calculus");
File temp = File.createTempFile("temp", ".tmp");
temp.deleteOnExit();
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write(convertListToContent(lines));
out.close();
File orig = new File("data/sample.txt");
fis = new FileInputStream(temp);
fos = new FileOutputStream(orig);
FileChannel src = fis.getChannel();
FileChannel dest = fos.getChannel();
dest.transferFrom(src, 0, src.size());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The method to convert a list of Strings into a single String
is pretty straight forward using Java 8: 使用Java 8将字符串列表转换为单个
String
方法非常简单:
private static String convertListToContent(List<String> lines) {
StringBuilder contentBuilder = new StringBuilder();
lines.forEach(l -> contentBuilder.append(l).append("\n"));
return contentBuilder.toString();
}
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.