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。但是對于小文件,沒問題。
添加回答
舉報