Java - 有没有办法打开一个文本文件,如果它已经不存在,并附加到它,如果它存在?

时间:2017-03-29 20:31:05

标签: java

我对Java很新,我遇到了这个问题。我希望java代码生成一个txt文件,如果它已经不存在,但是如果它已经存在,我希望PrintWriter使用FileWriter附加到它。这是我的代码:

编辑:我试图修复我的代码,但现在我收到了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;
    }
}

5 个答案:

答案 0 :(得分:0)

初始化myFile后添加以下行:

myFile.createNewFile(); // if file already exists will do nothing

答案 1 :(得分:0)

这是文件追加行的示例,如果文件不存在,则创建新文件。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileDemo {

    public static void main(String[] args) {
        try {
            String content = "This is my content which would be appended "
                    + "at the end of the specified file";
            //Specify the file name and path here
            File file = new File("myfile.txt");

            /* This logic is to create the file if the
         * file is not already present
             */
            if (!file.exists()) {
                file.createNewFile();
            }

            //Here true is to append the content to file
            FileWriter fw = new FileWriter(file, true);
            //BufferedWriter writer give better performance
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            //Closing BufferedWriter Stream
            bw.close();

            System.out.println("Data successfully appended at the end of file");

        } catch (IOException ioe) {
            System.out.println("Exception occurred:");
            ioe.printStackTrace();
        }
    }
}

答案 2 :(得分:0)

这是文件追加行的另一个示例,如果文件不存在,则创建新文件。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AppendFileDemo2 {

    public static void main(String[] args) {
        try {
            File file = new File("myfile2.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
            //This will add a new line to the file content
            pw.println("");
            /* Below three statements would add three 
           * mentioned Strings to the file in new lines.
             */
            pw.println("This is first line");
            pw.println("This is the second line");
            pw.println("This is third line");
            pw.close();

            System.out.println("Data successfully appended at the end of file");

        } catch (IOException ioe) {
            System.out.println("Exception occurred:");
            ioe.printStackTrace();
        }
    }
}

答案 3 :(得分:0)

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

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.next();
        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;
    }
}

我做的唯一改变是 String fileName = keyboard.next();来自//keyboard.nextLine() 上面的代码对我有用。希望这会有所帮助。

答案 4 :(得分:0)

另一个例子,这一次是使用try-with-resources并使用Files class创建BufferedWriter

public void write(File file, String text) throws IOException {
    Path path = file.toPath();
    Charset charSet = StandardCharsets.UTF_8;
    OpenOption[] options = new OpenOption[]{
        StandardOpenOption.CREATE, // Create a new file if it does not exist
        StandardOpenOption.WRITE,  // Open for write access
        StandardOpenOption.APPEND  // Bytes will be written to the end of
                                   // the file rather than the beginning
    };
    try (BufferedWriter bw = Files.newBufferedWriter(path, charSet, options)) {
        bw.write(text);
    }
}

以上示例可在GitHub上进行测试。

您还可以使用Files.write方法:

public void write(File file, List<String> lines) throws IOException {
    Path path = file.toPath();
    Charset charSet = StandardCharsets.UTF_8;
    OpenOption[] options = new OpenOption[]{
        StandardOpenOption.CREATE, // Create a new file if it does not exist
        StandardOpenOption.WRITE,  // Open for write access
        StandardOpenOption.APPEND  // Bytes will be written to the end of
                                   // the file rather than the beginning
    };
    Files.write(path, lines, charSet, options);
}