Latest News

Showing posts with label Basic Programming. Show all posts
Showing posts with label Basic Programming. Show all posts

Friday, September 30, 2016

September 30, 2016

How to create .txt file in java?

You can use bufferedWriter class to create a file and write contents into it.

Example:

public class WriteFromBufferWriter {
     public static void main(String[] args) throws IOException
 {

   File fl = new File("d:/myfile.txt");// location of file

   String str="Write this string to my file and update it";
 FileWriter fw = new FileWriter(fl.getAbsoluteFile()) ;
     BufferedWriter bw=new BufferedWriter(fw);
   fw.write(str);
   bw.close();
     System.out.println("Done");
 
  }

}

You can also use fileoutputstream class to create file.

Example:

class Fileoutputstream {

    public static void main(String[] args) throws IOException {
        
       FileOutputStream fout=new FileOutputStream("abc.txt");
       String s="My name";
       byte b[]=s.getBytes();
       fout.write(b);
       fout.close();
        System.out.println("Success");
        }
    Fileoutputstream(String a1) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
}