在java的netBeans IDE中写入文件

在java的netBeans IDE中写入文件,java,netbeans,Java,Netbeans,它没有写入文件。请帮我解决此问题尝试关闭BufferedWriter和FileWriter,如下所示: public class FileWriterClass { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { // TODO code applicati

它没有写入文件。请帮我解决此问题

尝试关闭BufferedWriter和FileWriter,如下所示:

public class FileWriterClass {
/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {
    // TODO code application logic here
    FileWriter fr = new FileWriter("hello.txt");
    BufferedWriter br = new BufferedWriter(fr);
    br.write("helllllllllllllllll");

  }    
}

完成数据写入后,应始终调用close

   br.write("helllllllllllllllll");
   br.close();
   fr.close();

因为您没有关闭资源,所以它是连续写的。 而且必须在Try-catch块中放入有风险的代码。必须使用关闭和刷新文件操作 更新代码:-


您需要确保写入程序已关闭,这会将缓冲区刷新到磁盘。您需要这样做,因为Java不保证对象将自动完成和关闭

为了让自己的生活更轻松,您可以使用,它将自动关闭写入程序,即使写入过程中出现异常

public class FileWriterClass {
public static void main(String[] args){
try{
FileWriter fr = new FileWriter("hello.txt");
BufferedWriter br = new BufferedWriter(fr);
br.write("helllllllllllllllll");
br.close();
}catch(IOException i){
i.printStackTrace();
}}}

您可以使用的实用方法。这样就不需要编写太多的样板代码

public class FileWriterClass {

    public static void main(String[] args) throws IOException {
        try (FileWriter fr = new FileWriter("hello.txt");
                BufferedWriter br = new BufferedWriter(fr)) {
            br.write("helllllllllllllllll");
        }

    }

}

您还需要关闭写入程序。写入程序将不会将数据刷新到文件中,除非您再次完全关闭它,否则您似乎缺少以下示例中的某些代码。如果在调用close语句之前引发异常,请使用try{//some code}catch{//some code}finally{br.close;fr.close;}@alias_boubou您假设br和fr不为null,并且在调用close时不会引发异常。您是对的,我们需要在close方法之前检查if语句中br和fr的可空性,以及在调用close语句之前是否引发异常?
public class FileWriterClass {

    public static void main(String[] args) throws IOException {
        try (FileWriter fr = new FileWriter("hello.txt");
                BufferedWriter br = new BufferedWriter(fr)) {
            br.write("helllllllllllllllll");
        }

    }

}
public class FileWriterClass {
    public static void main(String[] args) throws IOException {
        // path to the file to write, in this case the file
        // will be created in the current directory
        Path path = Paths.get("hello.txt");

        // the character set of the file
        Charset fileCharset = StandardCharsets.UTF_8;

        // the needed code to write to the file
        try (BufferedWriter bw = Files.newBufferedWriter(path, fileCharset)) {
            bw.write("hello NIO 2");
        }        
    }

}