gpt4 book ai didi

java - 使用 Java 将文本从一个文件反转并存储到另一个文件时减小大小

转载 作者:行者123 更新时间:2023-11-30 06:27:40 25 4
gpt4 key购买 nike

我做了这个家庭作业练习,从一个文本文件中读取文本并将其反转存储到另一个新文件中。这是代码:

import java.util.*;
import java.io.*;

public class FileEcho {

File file;
Scanner scanner;
String filename = "words.txt";
File file1 ;
PrintWriter pw ;
void echo() {
try {
String line;

file = new File( filename);
scanner = new Scanner( file );
file1 = new File("brabuhr.txt");
pw = new PrintWriter(file1);


while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();

pw.println(s);
}
scanner.close();
} catch(FileNotFoundException e) {
System.out.println( "Could not find or open file <"+filename+">\n"+e
);
}
}

public static void main(String[] args) {
new FileEcho().echo();
}
}

这是一张图片 Picture here

问题是:为什么新生成的文件大小相同,但字符却相反,却变小了?

如果有人能解释一下那就太好了,因为甚至我的教授也不知道为什么会这样。

附注;文件的上下文只是字典中的一些单词。在其他学生的计算机上也是如此,所以问题不是来 self 的计算机

最佳答案

问题是您从未关闭输出流pw,因此任何挂起的输出都不会写入底层文件。这可能会导致您的文件被截断。

您应该在finally 中或在尝试使用资源时使用pw.close() 关闭输出流。

try (pw = new PrintWriter(file1)) {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
}

您的实现可以简化为以下内容:

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileEcho {
void echo() throws IOException {
try (PrintWriter pw = new PrintWriter("brabuhr.txt")) {
Files.lines(Paths.get("words.txt"))
.map(s -> new StringBuilder(s).reverse().toString())
.forEach(pw::println);
}
}

public static void main(String[] args) throws IOException {
new FileEcho().echo();
}
}

在此示例中,我使用“try-with-resources”来自动关闭 PrintWriter pw

关于java - 使用 Java 将文本从一个文件反转并存储到另一个文件时减小大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46792925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com