2 回答
TA贡献1804条经验 获得超8个赞
好吧,你快到了。首先,我会使用 ajava.io.FileWriter将字符串写入文件。
如果您只是想将这些行写入文件,那么实际上没有必要在这里使用数组。
您还应该使用try-with-resources 语句来创建您的编写器。这确保escriptor.close()即使出现错误也会被调用。在这种情况下您也不需要调用.flush(),因为这将在句柄关闭之前完成。你打算自己做这件事很好,但一般来说,尽可能使用这种特殊的声明更安全。
import java.io.*;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
File f = new File("/tmp/output.txt");
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
sc.nextLine(); // Consume next empty line
try (FileWriter escriptor = new FileWriter(f)) {
for (int i = 0; i < mida; i++) {
System.out.println(String.format("Write line %d:", i + 1));
String paraula = sc.nextLine();
escriptor.write(String.format("%s\n", paraula));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
TA贡献1806条经验 获得超8个赞
如果您的文本文件很小并且不需要使用流阅读器/流编写器,您可以阅读文本,添加您想要的内容并重新编写。检查这个例子:
public class ReadWrite {
private static Scanner scanner;
public static void main(String[] args) throws FileNotFoundException, IOException {
scanner = new Scanner(System.in);
File desktop = new File(System.getProperty("user.home"), "Desktop");
System.out.println("Yo, which file would you like to edit from " + desktop.getAbsolutePath() + "?");
String fileName = scanner.next();
File textFile = new File(desktop, fileName);
if (!textFile.exists()) {
System.err.println("File " + textFile.getAbsolutePath() + " does not exist.");
System.exit(0);
}
String fileContent = readFileContent(textFile);
System.out.println("How many lines would you like to add?");
int lineNumber = scanner.nextInt();
for (int i = 1; i <= lineNumber; i++) {
System.out.println("Write line number #" + i + ":");
String line = scanner.next();
fileContent += line;
fileContent += System.lineSeparator();
}
//Write all the content again
try (PrintWriter out = new PrintWriter(textFile)) {
out.write(fileContent);
out.flush();
}
scanner.close();
}
private static String readFileContent(File f) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
return everything;
}
}
}
该示例的执行将是:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
4
Write line number #1:
Hello
Write line number #2:
Stack
Write line number #3:
Over
Write line number #4:
Flow
文件包含以下内容:
Hello
Stack
Over
Flow
如果您再次运行,输入以下内容:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
2
Write line number #1:
Hey
Write line number #2:
too
文本文件将包含:
Hello
Stack
Over
Flow
Hey
too
但是,如果您尝试处理大文件,您的内存将不够,因此OutOfMemoryError将抛出 an。但是对于小文件,没问题。
添加回答
举报