HOW TO CREATE A FILE AND WRITE TO A FILE IN JAVA?

Derek Honeybun

Total Post:17

Points:119
Posted by  Derek Honeybun
Java 
 745  View(s)
Ratings:
Rate this:
What's the simplest way to create and write to a (text) file in Java?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How to create a file and write to a file in Java?

    Writer writer = null;
    try {
        writer = new BufferedWriter(new OutputStreamWriter(
              new FileOutputStream("filename.txt"), "utf-8"));
        writer.write("Something");
    } catch (IOException ex) {
      // report
    } finally {
       try {writer.close();} catch (Exception ex) {/*ignore*/}
    }

    AND :
    public class Program {
        public static void main(String[] args) {
            String text = "Hello world";
            BufferedWriter output = null;
            try {
                File file = new File("example.txt");
                output = new BufferedWriter(new FileWriter(file));
                output.write(text);
            } catch ( IOException e ) {
                e.printStackTrace();
            } finally {
                if ( output != null ) output.close();
            }
        }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!