What is the simplest way to write a text file in Java?

前端 未结 9 1322
情歌与酒
情歌与酒 2021-01-01 09:55

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D

I searched the web and found this co

9条回答
  •  醉话见心
    2021-01-01 10:25

    Appending the file FileWriter(String fileName, boolean append)

    try {   // this is for monitoring runtime Exception within the block 
    
            String content = "This is the content to write into file"; // content to write into the file
    
            File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here
    
            // if file doesnt exists, then create it
            if (!file.exists()) {   // checks whether the file is Exist or not
                file.createNewFile();   // here if file not exist new file created 
            }
    
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
            BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
            bw.write(content); // write method is used to write the given content into the file
            bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect. 
    
            System.out.println("Done");
    
        } catch (IOException e) { // if any exception occurs it will catch
            e.printStackTrace();
        }
    

提交回复
热议问题