Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to write to text file in Java

2 Answers

0 votes
package javaapplication1;
 
import java.io.*;
 
public class JavaApplication1 
{
    public static void main(String[] args) 
    {
        try
        {
            File file = new File("d:\\test.txt");
            FileWriter fw = new FileWriter(file);
            try (BufferedWriter bw = new BufferedWriter(fw)) 
            {
                bw.write("Java Programming");
            }
            catch (Exception e)
            {
                System.out.println(e.toString());
            }
        }
        catch (Exception e) 
        {
            System.out.println("Error reading file: " + e.getMessage());   
        }
    }
}
 
/*
 
run:
 
test.txt
--------
Java Programming
 
*/

 



answered Jul 25, 2015 by avibootz
0 votes
package javaapplication1;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Example {
    
    public static void main(String[] args) {
       
        try {
            String filename = "d:\\test.txt";
            File file = new File(filename);
            
            if (!file.exists())
                file.createNewFile();
            
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            String s = "Java programming - write to file";
            bw.write(s);
            bw.close();
            
        } catch (IOException ex) {
            Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
   
   
/*
run:

check d:\test.txt file
    
*/

 



answered Jan 22, 2016 by avibootz
edited Jan 24, 2016 by avibootz

Related questions

1 answer 213 views
1 answer 249 views
1 answer 284 views
1 answer 235 views
1 answer 218 views
...