Java—如果文本文件不存在,是否有方法打开该文件,如果存在,是否有方法附加到该文件?

Java—如果文本文件不存在,是否有方法打开该文件,如果存在,是否有方法附加到该文件?,java,Java,我是Java新手,遇到了这个问题。如果txt文件不存在,我希望java代码生成一个txt文件,但是如果它存在,我希望PrintWriter使用FileWriter附加到它。这是我的密码: 编辑:我试图修复我的代码,但现在我得到IOException错误。我做错了什么? 编辑2:我认为我的代码是唯一的,因为我试图让它创建一个新的文件,如果文件不存在,并使它附加到现有的文件,如果它已经存在 import java.util.Scanner; import java.io.File; import j

我是Java新手,遇到了这个问题。如果txt文件不存在,我希望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;
    }
}

在初始化
myFile
后添加以下行:

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

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

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

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

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();
        }
    }
}
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();
        }
    }
}
我唯一的改变是 字符串文件名=keyboard.next();来自//keyboard.nextLine()
上面的代码对我有用。希望这能有所帮助。

另一个例子,这次使用并使用创建
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);
    }
}
上面的示例在带有测试的上可用

您还可以使用以下方法:

public void write(文件、列表行)引发IOException{
路径路径=file.toPath();
Charset Charset=StandardCharsets.UTF_8;
OpenOption[]选项=新OpenOption[]{
StandardOpenOption.CREATE,//如果不存在新文件,则创建新文件
StandardOpenOption.WRITE,//为写入访问打开
StandardOpenOption.APPEND//字节将写入
//文件,而不是开头
};
写入(路径、行、字符集、选项);
}

非常感谢您!顺便问一下,BufferedWriter比PrintWriter好有什么原因吗?我应该开始使用BufferedWriter而不是一直使用PrintWriter吗?另外,我试图通过您的解决方案修复我的代码,现在我得到了IOException。我做错了什么?可能是重复的谢谢,但我不这么认为,因为我试图让代码创建txt文件,如果它不存在。链接的问题提供了很多答案,也包含了创建丢失的文件。如果你仔细观察,你会发现,这个问题的很多答案都与链接问题的答案相同。这就是为什么我建议这个问题可能重复。啊,明白了。我会仔细看看。我确实略读了一遍,谢谢。在将keyboard.nextLine()更改为keyboard.next()之后,它对我也起了作用。您能简要解释一下为什么nextLine()会触发IOException吗?nextLine()会使此扫描仪前进超过当前行并返回跳过的输入。如果(!myFile.exists()){myFile.createNewFile();}导致IOException,则使用keyboard.nextLine()会使文件名为空,因此它会尝试创建一个空文件。@FakeOwl96您还有其他问题吗。如果你对我的解释感到满意,你介意接受我的回答吗?我完全忘记了,我会的!