Pages

Java write text file


Program below will ask user to enter their name and some description about them. After that it will write into a text file named MyTextFile.txt with .txt file's extension. You can try with other file format like .doc(Microsoft Word) or .rtf or others that you know to store text file. It's not mean if we write to text file, we must use a file with .txt as it's extension.

Description that i get from Wikipedia about text file is :

A text file (sometimes spelled "textfile": an old alternate name is "flatfile") is a kind of computer file that is structured as a sequence of lines.

So, it's mean a text file can hold any file's extension. Not only for .txt.

*********************************************************************
COMPLETE SOURCE CODE FOR : WriteTextFile.java
*********************************************************************


import java.io.File;
import java.io.PrintWriter;

import java.util.Scanner;

import java.awt.Desktop;

public class WriteTextFile
{
public static void main(String[]args)
{
Scanner scanUserInput=new Scanner(System.in);

File targetedFile=new File("MyTextFile.txt");

System.out.println("What is your name ?");
String name=scanUserInput.nextLine();

System.out.println("Put some description about yourself");
System.out.println("-----------------------------------");
String description=scanUserInput.nextLine();

try
{
PrintWriter pw=new PrintWriter(targetedFile);

pw.println("******************");
pw.println(name + "'s"+" profile");
pw.println("******************");
pw.println("Name : "+name);
pw.println();
pw.println("Description : "+description);

pw.flush();
pw.close();


Desktop.getDesktop().open(targetedFile);
}
catch(Exception exception)
{
System.out.println("Problem in file processing");
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************
Related Posts Plugin for WordPress, Blogger...

I Also Can Create T-Shirt Logo For You