Monday, 27 March 2017

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

JAVA based project, that can be used to hit DB using JDBC, from WSO2 ESB

Hi Buddies, Here is a small project that will enable you to hit MySQL DB using WSO2 ESB - https://github.com/namitsharma99/customM...