Writing a text file using java code

Hello Buddies.

Trying to write a text file from a java class this time.

Full code is available here -

https://github.com/namitsharma99/fileHandlingUsingJava/tree/master/src/com/java/code


Here it goes -

package com.java.code;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteTextFile {

public static void main(String[] args) {

String storeFileAt = "/home/namit/Downloads/newTextFile.txt";
try {
writeFile(storeFileAt);
} catch (IOException e) {
e.printStackTrace();
}

// output in the created file
// Hello, this is an example for java coding.
// Please refer to thecodebuddy.blogspot.in for more!
}

private static void writeFile(String storeFileAt) throws IOException {

FileOutputStream fileOutputStream = null;
File file = new File(storeFileAt);
fileOutputStream = new FileOutputStream(file);

String myContent = "Hello, this is an example for java coding. \n Please refer to thecodebuddy.blogspot.in for more!";

/*
* to avoid java.io.FileNotFoundException:
* /home/namit/writtenExamples/newTextFile.txt (No such file or
* directory), following check is used
*/
if (!file.exists())
file.createNewFile();

fileOutputStream.write(myContent.getBytes());

fileOutputStream.close();

}

}




Follow the comments in the code for a better understanding, and do try it out.

Your suggestions and try-outs are welcome.


Happy Coding!!

No comments:

Post a Comment

Featured post

Oracle SQL Scheduled Jobs - An Interesting Approach

  Oracle SQL Scheduled Jobs A DB Scheduler is the best way to automate any backend database job. For instance, if you want to process the p...