Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

In Java, I have text from a text field in a String variable called "text".

How can I save the contents of the "text" variable to a file?

1 Answer

0 votes
by (46k points)

check out this example to know how to write string content to a text file:

package com.java2novice.files;

 

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.Writer;

 

public class WriteToFile {

   public static void main(String[] args) {

        BufferedWriter bufferedWriter = null;

        try {

            String strContent = "This example shows how to save a string content to a text file";

            File myFile = new File("C:/MyTestFile.txt");

            // check if file exist, otherwise create the file before writing

            if (!myFile.exists()) {

                myFile.createNewFile();

            }

            Writer writer = new FileWriter(myFile);

            bufferedWriter = new BufferedWriter(writer);

            bufferedWriter.write(strContent);

        } catch (IOException e) {

            e.printStackTrace();

        } finally{

            try{

                if(bufferedWriter != null) bufferedWriter.close();

            } catch(Exception ex){            

            }

        }

    }

}

Related questions

0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...