Basic
of file handeling
File
handling capability made java a strong and robust programming language. One of
the most frequently used task in programming is writing to and reading from a
file. This function can achieve in java by include java’s io package. Classes
related to input and output are present in the JavaTM language
package java.io . Java technology uses "streams" as a general
mechanism of handling data. Input streams act as a source of data. Output
streams act as a destination of data. The file handeling capability can achive
in java by two types
1)Byte
Stream
2)Character
Stream.
You
are probably aware that Java is one of the most popular programming languages
that people use. It is so popular because it can be used so widely from
application software to web applications and capable to read data from various
device and application such as from Network socket,another file, other embaded
device and also in XML format.
To
write anything to a file first of all we need a file name we want to use. The file
name is a simple string like like this:
- String fileName = "myfile.txt";
If
you want to write in a file which is located elsewhere you need to define the
complete file name and path in your fileName variable:
complete file name and path in your fileName variable:
- String fileName = "c:\\path\\test.txt";
However
if you define a path in your file name then you have to take care the path
separator. On windows system the '\' is used and you need to backslash it so
you need to write '\\', in Unix,Linux systems
the separator is a simple slash '/'.
the separator is a simple slash '/'.
Opening
a file
To
open a file for writing use the FileWriter class and create an instance from
it.
The file name is passed in the constructor like this.New operator is used for allocating memory to object.
The file name is passed in the constructor like this.New operator is used for allocating memory to object.
- FileWriter writer = new FileWriter(fileName);
This
code opens the file in overwrite mode if file already exhists. If you want to
append to the file then
you need to use an other constructor like this:
you need to use an other constructor like this:
- FileWriter writer = new FileWriter(fileName,true);
Besides
this the constructor can throw an IOException so we put all of the code inside
a try-catch block.
a try-catch block.
The
syntax is simple
Try{
FileWriter
writer = new FileWriter(fileName,true);
}
Catch(Exception
ex)
{
System.out.println(“Exception
accur”);
}
Write
to a text file
public void writeFile() {
String fileName =
"c:\\test.txt";
try {
FileWriter writer = new
FileWriter(fileName,true);
writer.write("Test text.");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This
program showing simple file write operation.
Reading
the file content
File
reading operation can achive by two types 1)Data input stream 2)File input
stream
File
reading using data input stream
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
FileInputStream fstream = new FileInputStream("C:/myfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
class FileRead {
public static void main(String args[]) {
try {
FileInputStream fstream = new FileInputStream("C:/myfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
This
program use DataInputStream for reading text file line by line with a
BufferedReader.
DataInputStream-This class read binary primitive data
types in a machine-independent way.
BufferedReader-This class read the text from a file
line by line with it's readLine() method.
File reading using file input stream.
import java.io.*;
public class FileRead {
public static void main(String[] args) {
File file = new File("C:/file.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println(strContent.toString());
}
}
public class FileRead {
public static void main(String[] args) {
File file = new File("C:/file.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println(strContent.toString());
}
}
FileInputStream- This class reads bytes from the given
file name.
read()-The read() method of FileInputStream
class reads a byte or array of bytes from the file. It returns -1 when
the end-of-file has been reached.
StringBuffer- This class is used to store character
strings that will be changed.
append()-The append() of StringBuffer
class appends or adds the string representation of the char argument to this
sequence.
Copy
one file into another file
import java.io.*; //Package import
public class CopyFile {
private static void copyfile() {
try {
File f1 = new File("C:/file.txt"); //Source file
File f2 = new File("C:/new.txt"); //Destination file
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2, true);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (Exception ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
copyfile();
}
}
public class CopyFile {
private static void copyfile() {
try {
File f1 = new File("C:/file.txt"); //Source file
File f2 = new File("C:/new.txt"); //Destination file
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2, true);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (Exception ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
copyfile();
}
}
Program to count words of a file
import java.io.*;
import java.util.*;
public class
FileCountwords {
public static void main(String[] args) throws Exception {
BufferedReader br = new
BufferedReader(new FileReader("C:/file.txt"));
String line = "", str =
"";
int count = 0;
while ((line = br.readLine()) != null) {
str += line +
" ";
}
StringTokenizer st = new
StringTokenizer(str);
while (st.hasMoreTokens()) {
String s =
st.nextToken();
count++;
}
System.out.println("File has " +
count + " words.");
}
}
It will print the number of words into a file.
No comments:
Post a Comment