Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

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
*********************************************************************

Java and pathname

Before i go through about file's operation, i want to share with you about "pathname" keyword. In java there has lot of methods play with pathname.

For example :
When we want to create a file instance like below
******************************************
File myFile=new File("c:\\mytext.txt");
******************************************

"c:\\mytext.txt" is a pathname for mytext.txt that locate in c drive.Origin for c:\\mytext.txt is c:\mytext.txt.We use two backslash to prevent syntax error when we compile it.

So, what is pathname ?
  • A pathname is a string that describes what directory the file is in, as well as the name of the file.

Call jar file from a java program


Complete source code below will show you, how to open or call a jar file (java executable file) from a java program.

Download MyJarFile.jar that will use in this tutorial.Place this file at the same location with java file below before compile and execute it.

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


import java.awt.Desktop;

import java.io.File;

public class CallJarFile
{
public static void main(String[]args)
{
try
{
//Call MyJarFile.jar
Desktop.getDesktop().open(new File("MyJarFile.jar"));
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Java play wav file

Complete source code below will show you, how to play wav file in java.

Click here to download Star-Wars-4118.wav that will use with this code. Place this wav file same location with this source code file.

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


import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

public class PlayWavFile
{
public static void main(String[]args)
{
String filename="Star-Wars-4118.wav";

int EXTERNAL_BUFFER_SIZE = 524288;

File soundFile = new File(filename);

if (!soundFile.exists())
{
System.err.println("Wave file not found: " + filename);
return;
}

AudioInputStream audioInputStream = null;
try
{
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
}
catch(Exception e)
{
e.printStackTrace();
return;
}

AudioFormat format = audioInputStream.getFormat();

SourceDataLine auline = null;

//Describe a desired line
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

try
{
auline = (SourceDataLine) AudioSystem.getLine(info);

//Opens the line with the specified format,
//causing the line to acquire any required
//system resources and become operational.
auline.open(format);
}
catch(Exception e)
{
e.printStackTrace();
return;
}

//Allows a line to engage in data I/O
auline.start();

int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];

try
{
while (nBytesRead != -1)
{
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
{
//Writes audio data to the mixer via this source data line
//NOTE : A mixer is an audio device with one or more lines
auline.write(abData, 0, nBytesRead);
}
}
}
catch(Exception e)
{
e.printStackTrace();
return;
}
finally
{
//Drains queued data from the line
//by continuing data I/O until the
//data line's internal buffer has been emptied
auline.drain();

//Closes the line, indicating that any system
//resources in use by the line can be released
auline.close();
}
}
}


***********************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************

Set file to Read-only in java

Complete source code below will show you, how to set a file to Read-only in java.

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


import java.io.File;

public class SetFileReadOnly
{
public static void main(String[]args)
{
File myFile=new File("MyFile.txt");

//Set MyFile.txt to Read-only
myFile.setReadOnly();
}
}


******************************************************************
JUST COMPILE AND EXECUTE IT
******************************************************************

Click here to download MyFile.txt

Note : Put MyFile.txt with java file above at the same location.

Open file using JFileChooser

Complete source code below will show you, how to open file using JFileChooser.

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


/*
*Desktop class only can get when you use JDK 6
*/
import java.awt.Desktop;

import javax.swing.JFileChooser;

import java.io.File;

public class OpenFileUsingJFileChooser
{
public static void main(String[]args)
{
//Create a file chooser
JFileChooser fileChooser=new JFileChooser();

//File chooser will appear in no windows parent
int a=fileChooser.showOpenDialog(null);

//Action that will take when user click open button
if(a==JFileChooser.APPROVE_OPTION)
{
//Get file that want to open
File fileToOpen=fileChooser.getSelectedFile();

try
{
//Open file using suitable program on computer.
//You don't need to tell what program to use.
//Java will select default program that your
//computer use to open the file.
//In windowsXP you can see what
//program that your computer use to open
//a file by right click on file,
//choose properties and see at
//Opens with : ProgramNameToOpenTheFile
Desktop.getDesktop().open(fileToOpen);
}
catch(Exception exception)
{
System.out.println("Problem occour when to open the file");
}
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Open any file or folder using Desktop class

Complete source code below will show you, how to open C:\ drive using Desktop class. Desktop class is only can get when you use jdk 6.

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


/*
*If you want to use Desktop class,
*you must make sure that jdk version
*that you use is 6. This facilities
*is exist in jdk 6.
*/
import java.awt.Desktop;

import java.io.File;

public class OpenFileUsingDesktopClass
{
public static void main(String[]args)
{
try
{
//Open C:\ drive
//Make sure that you change \ to \\
//You can change to other file or folder that you want
//Example for file that you want to open:
//C:\Sunset.jpg
//So, change C:\\ below to
//C:\\Sunset.jpg
Desktop.getDesktop().open(new File("C:\\"));
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


******************************************************************
JUST COMPILE AND EXECUTE IT
******************************************************************


Click here to download jdk6
Click here to download jdk6 documentation

Open any file or folder in java

Complete source code will show you, how to open any files or folders using java in windows.What you must know is :


rundll32 SHELL32.DLL,ShellExec_RunDLL File_Or_Folder_To_Open


What is rundll32.exe And Why Is It Running?


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


public class OpenFileUsingJava
{
public static void main(String[]args)
{
try
{
//Path for folder or file that you want to open
//In my case i will open C:\ drive
//So create a String like below
//Don't forget to change \ to \\
String a="C:\\";

//Execute command
//Command that you must know : rundll32 SHELL32.DLL,ShellExec_RunDLL File_Or_Folder_To_Open
Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL \""+a+"\"");
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


****************************************************************
JUST COMPILE AND EXECUTE IT
****************************************************************

Open a text file into JTextArea

Complete source code below will show you, how to open a text file with file extension (.txt) into JTextArea.

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


import javax.swing.*;

import java.util.*;

import java.io.*;

public class OpenTextFileIntoJTextArea
{
public static void main(String[]args)
{
try
{
//Read a text file named MyTextFile.txt
//You can download this text file at the link below
//You also can change to other text file by change it's name
//Don't forget to put .txt
//If your text file locate at other location,
//you must put it full location.
//For example :
//C:\\Documents and Settings\\evergreen\\MyTextFile.txt
FileReader readTextFile=new FileReader("MyTextFile.txt");

//Create a scanner object from FileReader
Scanner fileReaderScan=new Scanner(readTextFile);

//Create a String that will store all text in the text file
String storeAllString="";

//Put all text from text file into created String
while(fileReaderScan.hasNextLine())
{
String temp=fileReaderScan.nextLine()+"\n";

storeAllString=storeAllString+temp;
}

//Set JTextArea text to created String
JTextArea textArea=new JTextArea(storeAllString);

//Set JTextArea to line wrap
textArea.setLineWrap(true);

//Set JTextArea text to word wrap
textArea.setWrapStyleWord(true);

//Create scrollbar for text area
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

//Create a window using JFrame with title ( Open text file into JTextArea )
JFrame frame=new JFrame("Open text file into JTextArea");

//Add scrollbar into JFrame
frame.add(scrollBarForTextArea);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(500,500);

//Make JFrame locate at center on screen
frame.setLocationRelativeTo(null);

//Make JFrame visible
frame.setVisible(true);
}
catch(Exception exception)
{
//Print Error in file processing if it can't process your text file
System.out.println("Error in file processing");
}
}
}


**************************************************************
JUST COMPILE AND EXECUTE IT
**************************************************************

CLICK HERE TO DOWNLOAD MyTextFile.txt

Set file type in JFileChooser

Complete source code below will show you, how set file type that should be display in a JFileChooser. Source code below will display all directories and text files only.

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


import javax.swing.filechooser.FileFilter;

import javax.swing.JFileChooser;

import java.io.File;

public class SetJFileChooserFileType
{
public SetJFileChooserFileType()
{
//Create a file chooser from JFileChooser
JFileChooser fileChooser=new JFileChooser();

//Set file type that should be display by set JFileChooser's file filter
fileChooser.setFileFilter(new TypeOfFile());

//Show JFileChooser
int a=fileChooser.showDialog(null,"Open Text File");
}

//Class TypeOfFile
class TypeOfFile extends FileFilter
{
//Type of file that should be display in JFileChooser will be set here
//We choose to display only directory and text file
public boolean accept(File f)
{
return f.isDirectory()||f.getName().toLowerCase().endsWith(".txt");
}

//Set description for the type of file that should be display
public String getDescription()
{
return ".text files";
}
}

public static void main(String[]args)
{
SetJFileChooserFileType sjfcft=new SetJFileChooserFileType();
}
}


***************************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************************

How to know all method that contain in a java class file ???

How to know all method that contain in a java class file ???
Source code below will list all method that contain in java predefined class, named Object. For your information ,all java program will be subclass to Object class. If you write a java program, your java program will be subclass to Object class automatically. You may be, not see how it's happen but it is truly happen.

How to make java program output to a file instead of command prompt like usual ???

This source code will show you how to make java output that print in command prompt will be print in a file instead of command prompt.

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


import java.io.PrintStream;

public class PutCommandPromptOutputToFile
{
public static void main(String[]args)
{
try
{
PrintStream newOuputChannel=new PrintStream("output.txt");
System.setOut(newOuputChannel);

System.out.println("HI");
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


**************************************************************
JUST COMPILE AND EXECUTE IT
**************************************************************

RELAXING NATURE VIDEO