我對Java很新,而且遇到了這個問題。如果它不存在,我想讓java代碼生成一個txt文件,但如果它確實存在,我希望PrintWriter使用FileWriter將其附加到它。這裏是我的代碼:Java - 有沒有辦法打開一個文本文件,如果它不存在,並附加到它,如果它確實存在?
編輯:我試圖解決我的代碼,但現在我得到IOException錯誤。我在這裏做錯了什麼? 編輯2:我認爲我的代碼是獨一無二的,因爲我試圖在文件不存在的情況下創建一個新文件,並且在現有文件已經存在的情況下添加它。
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
/**
* Created by FakeOwl96 on 3/28/2017.
*/
public class AreaOfCircle {
private static double PI = Math.PI;
private double radius;
private static double area;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
AreaOfCircle a = new AreaOfCircle();
System.out.print("Type in the radius of circle: ");
a.radius = keyboard.nextDouble();
getArea(a.radius);
System.out.print("Name of the txt file you want to create:");
String fileName = keyboard.nextLine();
keyboard.nextLine();
try {
File myFile = new File(fileName);
if (!myFile.exists()) {
myFile.createNewFile();
}
FileWriter fw = new FileWriter(myFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("The area of the circle is " + area + ".\n");
bw.close();
}
catch (IOException e) {
System.out.println("IOException Occured");
e.printStackTrace();
}
}
public static void getArea(double n) {
area = n * PI;
}
}
[如何將文本追加到Java中的現有文件]可能的重複(http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java ) –
謝謝,但我不這麼認爲,因爲我試圖讓代碼創建txt文件,如果它不存在。 – FakeOwl96
鏈接的問題提供了很多答案,還包含缺失文件的創建。如果仔細觀察,你會發現,這個問題上的很多答案與鏈接問題中的答案相同。這就是爲什麼我提出這個問題,因爲__possible__重複。 –