在Java中,沒有現成的writeLine方法,但是可以使用write方法和println方法來實現類似的功能。
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter fileWriter = new FileWriter("output.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello, World!");
bufferedWriter.newLine(); // 寫入換行符
bufferedWriter.write("This is a new line.");
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
PrintWriter printWriter = new PrintWriter(new FileOutputStream("output.txt"));
printWriter.println("Hello, World!");
printWriter.println("This is a new line.");
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
這兩種方法都可以實現在文件中寫入一行文本并換行。使用write方法需要手動添加換行符,而使用println方法會在每次寫入后自動換行。