0
1
2
Sr. no Table of content Page no.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
Work Distribution.
Program f...
Files Theory:
• Files are a primary source and destination for data within many
programs. Although there are severe restri...
TYPES OF FILES:
I. TEXT FILE : A text file contains visible characters.
We can see the contents of file on monitor or
take...
• Methods of File Class:
boolean canRead()
Tests whether the application can read the file denoted by this abstract pathna...
boolean delete()
Deletes the file or directory denoted by this abstract pathname.
void deleteOnExit()
Requests that the fi...
Program : Files:
File fis=new File("Input.txt");
System.out.println("File Name is "+fis.getName());
System.out.println("n"...
RandomAccessFile:
The RandomAccessFile class supported by the java.io package
allows us to create files that can be used f...
Program :RandomAccessFile:
RandomAccessFile RA;
try
{
RA = new
RandomAccessFile("BookTitle.txt","rw");
RA.seek(RA.length()...
FileInputStream:
• The FileInputStream class creates an InputStream that you can use to read bytes
from a file. Its two mo...
Methods of Input stream:
• Methods:
• int available( )
• void close( )
• void mark(int numBytes)
• boolean markSupported( ...
Program: File Input Stream
int size;
FileInputStream f1=new FileInputStream("Input.txt");
System.out.println("nnn");
Syste...
Program: File Input Stream
System.out.println(new String(bytearray,0,50));
System.out.println("skipping 50 bytes.............
FileOutputStream
• FileOutputStream creates an OutputStream that you can use to write
bytes to a file. Its most commonly u...
Program : FileOutputStream
byte data[]="This is a string of text.".getBytes();
FileOutputStream fin=new
FileOutputStream("...
BufferedInputStream
• Buffering I/O is a very common performance optimization. Java’s
BufferedInputStream class allows you...
Program: BufferedInputStream
String s = "This is a © copyright symbol " +"but this is &copy not.n";
byte buf[] = s.ge...
Program: BufferedInputStream
else
{
marked = false;
}
break;
case ';':if (marked)
{
marked = false;
System.out.print("(c)"...
Program: BufferedInputStream
case ' ':if (marked)
{
marked = false;
f.reset();
System.out.print("&");
}
else
System.out.pr...
COPY COMMAND
• The command copies computer files from one directory to another.
The destination defaults to the current wo...
Program: Copy Byte
// declare input and output file streams
FileInputStream inputfile = null; // Input stream
FileOutputSt...
Program: Copy Byte
while(ByteRead!=-1);
}
catch(FileNotFoundException e)
{
System.out.println(" File not found");
}
catch(...
Algorithm For Count Char:
 Step 1: Start
 Step2: Create file stream i..
 Step3: Open Input.txt.
 Step4: Read and write...
Program: Count Char
File InFile = new File("Input.txt");
int count=0;
FileReader inp = null; // creates file
stream i
try
...
Program: Count char
while((cho=inp.read())!=-1)
{
if((cho!=' ') && (cho>=65 &&
cho<=143))
count=count+1;
}
System.out.prin...
FileReader
• The FileReader class creates a Reader that you can use to read the contents of a
file. Its two most commonly ...
Methods Of File Reader
• Method
o abstract void close( )
o void mark(int numChars)
o boolean markSupported( )
o int read( ...
Program:File Reader
FileReader fr=new FileReader("Input.txt");
char data1[]=new char[1024];
int charread=fr.read(data1)
Sy...
FILE WRITER
• FileWriter creates a Writer that you can use to write to a file. Its most commonly
used constructors are sho...
Program: File Writer
char data2[]={'r','i','z','v','i',' ','c','o','l','l','e','g','e'};
FileWriter fo=new FileWriter("fil...
INPUTSTREAMREADER:
• An InputStreamReader is a bridge from byte streams to character streams: It
reads bytes and decodes t...
Program:InputStreamReader:
int character;
InputStreamReader finp=new
InputStreamReader(System.in);
while((character=finp.r...
Read Write Bytes:
• Most often used stream classes are FileInputStream and
FileOutputStream, which create byte stream link...
Program: Read write Byte
byte [] name = new byte[LINELENGTH];
byte [] number = new byte[LINELENGTH];
FileOutputStream fos ...
Program: Read Write Byte
System.out.println("Enter Number : ");
readLine(number);
for( int i = 0; number[i] != 13; i++)
{
...
Read Write Character:
• The subclasses of Reader and Writer implement streams that can
handle character
• The two subclass...
Program: Read Write Character
File InFile2=new File("Input.txt");
File OutFile=new File("Output3.txt");
FileReader inr =nu...
Program: Read Write Character
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
inr.close()...
Write Bytes:
• The subclasses of Reader and Writer implement streams that can handle
bytes.
• The two subclasses used for ...
Program: Write Bytes
bytecities[]={'D','E','L','H','I','n','M','A','D','R','A','S','n','L','O','N','D'
,'O','N','n'};
File...
Writing String to a File:
• In this program we, write to the file and so we create a new Print
Stream object that takes as...
Program: Writing String to a File:
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print...
43
List Of Choice
import java.io.*;
public class Pro1
{
static int LINELENGTH = 80;
public static void main(String[] args) th...
Output of Choice List
45
Choice 1: Buffered Input Stream
case 1:
String s = "This is a &copy; copyright symbol " +"but this is &copy not.n";
byte b...
case ';':if (marked)
{
marked = false; System.out.print("(c)");
}
else
System.out.print((char) c);
break;
case ' ':if (mar...
Output of Choice 1
48
Choice 2: Append Demo
case 2: RandomAccessFile RA;
try
{
RA = new RandomAccessFile("BookTitle.txt","rw");
RA.seek(RA.lengt...
Output of Choice 2
50
Choice 3: Copy Bytes
Case 3: // declare input and output file streams
FileInputStream inputfile = null; // Input stream
Fi...
catch(FileNotFoundException e)
{
System.out.println(" File not found");
}
catch(IOException e)
{
System.out.println(" I/O ...
Output of Choice 3
53
Choice 4: To Count Char
Case 4: File InFile = new File("Input.txt");
int count=0;
FileReader inp = null; // creates file s...
Ouput of Choice 4
55
Choice 5: File Input Stream
Case 5: int size;
FileInputStream f1=new FileInputStream("Input.txt");
System.out.println("nnn...
Output of Choice 5:
57
Choice 6:File Output Stream
Case 6: byte data[]="This is a string of text.".getBytes();
FileOutputStream fin=new FileOutpu...
Output of Choice 6:
59
Choice 7: File Reader
case 7: FileReader fr=new FileReader("Input.txt");
char data1[]=new char[1024];
int charread=fr.read...
Output of Choice 7
61
Choice 8: File Properties
case 8:
File fis=new File("Input.txt");
System.out.println("File Name is "+fis.getName());
Syste...
Output of Choice 8
63
Choice 9: File Writer
case 9:
char data2[]={'r','i','z','v','i',' ','c','o','l','l','e','g','e'};
FileWriter fo=new FileWr...
Output of Choice 9
65
Choice 10: Input Stream Reader
case 10:
int character;
InputStreamReader finp=new InputStreamReader(System.in);
while((cha...
Output of Choice 10
67
Choice 11: Read Write Bytes
case 11:
try
{
byte [] name = new byte[LINELENGTH];
byte [] number = new byte[LINELENGTH];
Fil...
System.out.println("Enter Number : ");
readLine(number);
for( int i = 0; number[i] != 13; i++)
{
fos.write(number[i]);
}
f...
private static void readLine(byte [] line) throws IOException
{
int i = 0, b = 0;
while(i < LINELENGTH - 1 && (b = System....
Output of Choice 11
71
Choice 12: Read Write Character
case 12:
File InFile2=new File("Input.txt");
File OutFile=new File("Output3.txt");
FileRea...
finally
{
try
{
inr.close();
or.close();
}
catch(IOException e)
{
}
}
break;
73
Output of Choice 12
74
Choice 13: Write Bytes
case 13:
byte cities[]={'D','E','L','H','I','n','M','A','D','R','A','S','n','L','O','N','D','O','N'...
Output of Choice 13:
76
Choice 14: Write String To File
case 14:
FileOutputStream out;
PrintStream p;
try
{
out = new FileOutputStream("myfile.txt...
Output of Choice 14
78
Bibliography:
Websites:
www.google.com
www.wikipedia.com
www.sourcecode.com
Books:
Programming in Java by
Balguruswamy.
...
Upcoming SlideShare
Loading in...5
×

Files Systems

164

Published on

Project on File Systems

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
164
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
10
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Files Systems"

  1. 1. 1
  2. 2. 2 Sr. no Table of content Page no. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. Work Distribution. Program for Files properties( Theory, types, Program). Program for Append Demo( Random Access File). Program for FileInputStream. Program for FileOutputStream. Program for Buffered Input Stream. Write a program for Copybytes. Write a program for Count Char. Write a program for FileReader. Write a program for File Writer. Program for Input Stream Reader. Program for Read Write Bytes. Program for Read Write Character. Program for Write Bytes. Program for Write String To File. Program with Output. Bibliography. 3 4-6 7-8 9-12 13-14 15-18 19-21 22-24 26-27 28-29 30-31 32-34 35-37 38-39 40-41 42-77 78
  3. 3. Files Theory: • Files are a primary source and destination for data within many programs. Although there are severe restrictions on their use within applets for security reasons, files are still a central resource or storing persistent and shared information. • Although most of the classes defined by java.io operate on streams, the File class does not. It deals directly with files and the file system. • That is, the File class does not specify how information is retrieved from or stored in files; it describes the properties of a file itself. • A File object is used to obtain or manipulate the information associated with a disk file, such as the permissions, time, date, and directory path, and to navigate subdirectory hierarchies. • The following constructors can be used to create File objects: • File(String directoryPath) • File(String directoryPath, String filename) • File(File dirObj, String filename) • File(URI uriObj) 3
  4. 4. TYPES OF FILES: I. TEXT FILE : A text file contains visible characters. We can see the contents of file on monitor or take its printout or edit it using any of the text editors. E.g. A file containing java program. I. BINARY FILE : A byte consists of 8bits. We can have total of 256 combination of 8 bits. An ASCII is a 7bit code represented in 8bits. A byte may contain a value that may either not be a valid ASCII code or it can not be displayed. E.g.. An executable file. 4
  5. 5. • Methods of File Class: boolean canRead() Tests whether the application can read the file denoted by this abstract pathname. boolean canWrite() Tests whether the application can modify to the file denoted by this abstract pathname. int compareTo(File pathname) Compares two abstract pathnames lexicographically. int compareTo(Object o) Compares this abstract pathname to another object. boolean createNewFile() Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. static File createTempFile(String prefix, String suffix) Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. static File createTempFile(String prefix, String suffix, File directory) Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. 5
  6. 6. boolean delete() Deletes the file or directory denoted by this abstract pathname. void deleteOnExit() Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. boolean equals(Object obj) Tests this abstract pathname for equality with the given object. boolean exists() Tests whether the file or directory denoted by this abstract pathname exists. File getAbsoluteFile() Returns the absolute form of this abstract pathname. String getAbsolutePath() Returns the absolute pathname string of this abstract pathname. File getCanonicalFile() Returns the canonical form of this abstract pathname. String getCanonicalPath() Returns the canonical pathname string of this abstract pathname. String getName() Returns the name of the file or directory denoted by this abstract pathname. 6
  7. 7. Program : Files: File fis=new File("Input.txt"); System.out.println("File Name is "+fis.getName()); System.out.println("n"); System.out.println(fis.isFile() ? "Is File" : "Is Directory"); System.out.println("n"); System.out.println("File Size: "+fis.length()); System.out.println("n"); System.out.println("Path: "+ fis.getPath()); System.out.println("n"); System.out.println("Absolute path: "+fis.getAbsolutePath()); System.out.println("n"); System.out.println("File Last modified: "+fis.lastModified()); System.out.println("n"); System.out.println(fis.canRead() ? "File Can Read" : "File Cannot be Read"); System.out.println("n"); System.out.println(fis.canWrite() ? "File Can Write" : "File Cannot Be Written"); 7
  8. 8. RandomAccessFile: The RandomAccessFile class supported by the java.io package allows us to create files that can be used for reading and writing data with random access. That is, we can jump around in the file while using the file. Such files are known as random access files. A file can be created and opened for random access by giving a mode string as a parameter to the constructor when we open the file. Algorithm: Step 1: Start Step2: Create a file(“BookTitle.txt”) Step3: Go to the end of file to calculate length Step4: Append data Step5:close. 8
  9. 9. Program :RandomAccessFile: RandomAccessFile RA; try { RA = new RandomAccessFile("BookTitle.txt","rw"); RA.seek(RA.length()); // Go to the end RA.writeBytes("Studying Dsf"); // Append data RA.close(); } catch(IOException e) { System.out.println(e); } 9
  10. 10. FileInputStream: • The FileInputStream class creates an InputStream that you can use to read bytes from a file. Its two most common constructors are shown here: • FileInputStream(String filepath) FileInputStream(File fileObj) • • Either can throw a FileNotFoundException. Here, filepath is the full path name of a file, and fileObj is a File object that describes the file. • The following example creates two FileInputStreams that use the same disk file and each of the two constructors: • FileInputStream f0 = new FileInputStream("/autoexec.bat") File f = new File("/autoexec.bat"); • FileInputStream f1 = new FileInputStream(f); ALGORITHM:  Step 1: Start  Step2: Initialize character  Step3: Take input from keyboards  Step4: I/p stream does not become available until the user press enter key.  Step5:close. 10
  11. 11. Methods of Input stream: • Methods: • int available( ) • void close( ) • void mark(int numBytes) • boolean markSupported( ) • int read( ) • void reset( ) • Description: • Returns the number of bytes of input currently available for reading. • Closes the input source. Further read attempts will generate an IOException. • Places a mark at the current point in the input stream that will remain valid until numBytes bytes are read. • Returns true if mark( )/reset( ) are supported by the invoking stream. • Returns an integer representation of the next available byte of input. –1 is returned when the end of the file is encountered. • Resets the input pointer to the previously set mark. 11
  12. 12. Program: File Input Stream int size; FileInputStream f1=new FileInputStream("Input.txt"); System.out.println("nnn"); System.out.println("Available bytes : " + (size=f1.available())); System.out.println("Reading 50 Bytes.........."); byte bytearray[]=new byte[50]; if(f1.read(bytearray)!=50) { System.out.println("could not get 50 bytes"); } 12
  13. 13. Program: File Input Stream System.out.println(new String(bytearray,0,50)); System.out.println("skipping 50 bytes..........."); f1.skip(50); System.out.println("Reading 50 bytes........"); if(f1.read(bytearray)!=50) { System.out.println("could not get 50 bytes"); } System.out.println(new String(bytearray,0,30)); f1.close(); 13
  14. 14. FileOutputStream • FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most commonly used constructors are shown here: • FileOutputStream(String filePath) FileOutputStream(File fileObj) FileOutputStream(String filePath, boolean append) FileOutputStream(File fileObj, boolean append). • The first, file1.txt, will contain every other byte from the sample. The second, file2.txt, will contain the entire set of bytes. The third and last, file3.txt, will contain only the last quarter. Unlike the FileInputStream methods, all of the FileOutputStream methods have a return type of void. In the case of an error, these methods will throw an IOException. ALGORITHM:  Step 1: Start  Step2: Initialize character  Step3: It checks for the character present in the input file.  Step4: Computer Writes the output in the File11.txt.  Step5:close. 14
  15. 15. Program : FileOutputStream byte data[]="This is a string of text.".getBytes(); FileOutputStream fin=new FileOutputStream("Output.txt"); for(int i=0;i<data.length;i++) { fin.write(data[i]); } FileOutputStream f2=new FileOutputStream("Output2.txt"); f2.write(data); FileOutputStream f3=new FileOutputStream("Output3.txt"); f3.write(data,5,10); fin.close(); f2.close(); f3.close(); 15
  16. 16. BufferedInputStream • Buffering I/O is a very common performance optimization. Java’s BufferedInputStream class allows you to “wrap” any InputStream into a buffered stream and achieve this performance improvement. • BufferedInputStream has two constructors: • BufferedInputStream(InputStream inputStream) BufferedInputStream(InputStream inputStream, int bufSize) • Buffering an input stream also provides the foundation required to support moving backward in the stream of the available buffer. Beyond the read( ) and skip( ) methods implemented in any InputStream, BufferedInputStream also supports the mark( ) and reset( ) methods. This support is reflected by BufferedInputStream.markSupported( ) returning true. ALGORITHM: o Step 1: Start o Step2: Create ByteArrayInputStream object. o Step 3: Create BufferedInputStream object. o Step3: Use switch case. o Step4: Break; o Step5:close. 16
  17. 17. Program: BufferedInputStream String s = "This is a &copy; copyright symbol " +"but this is &copy not.n"; byte buf[] = s.getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(buf); BufferedInputStream f = new BufferedInputStream(in); int c; boolean marked = false; while ((c = f.read()) != -1) { switch(c) { case '&':if (!marked) { f.mark(32); marked = true; } 17
  18. 18. Program: BufferedInputStream else { marked = false; } break; case ';':if (marked) { marked = false; System.out.print("(c)"); } else System.out.print((char)c); break; 18
  19. 19. Program: BufferedInputStream case ' ':if (marked) { marked = false; f.reset(); System.out.print("&"); } else System.out.print((char) c); break; default:if (!marked) System.out.print((char) c); break; } } 19
  20. 20. COPY COMMAND • The command copies computer files from one directory to another. The destination defaults to the current working directory. If more than one source file is indicated, the destination must be a directory. • Files may be copied to device files (e.g. copy letter.txt lpt1 sends the file to the printer on lpt1. copy letter.txt con would output to std out like the type command. Note that copy page1.txt+page2.txt book.txt will concatenate the files and output them as book.txt. Which is just like the cat command. E.g. Of copy command is copying byte, copying char…. ALGORITHM FOR COPY BYTE:  Step1: Declare input and output stream.  Step2: Declare a variable to hold byte.  Step3: Connect input file to Input.txt  Step4: Connect out file to Outfile.txt.  Step5: Reading bytes from Input.txt and writing to Output.txt.  Step6: Stop. 20
  21. 21. Program: Copy Byte // declare input and output file streams FileInputStream inputfile = null; // Input stream FileOutputStream outputfile = null; // Output stream //Declare a variable to hold a byte byte ByteRead; try { // Connect inputfile to Input.txt inputfile = new FileInputStream("Input.txt"); // Connect outfile to Output.txt outputfile = new FileOutputStream("Output.txt"); // Reading bytes from file1.dat and Writing to file2.dat do { ByteRead =(byte) inputfile.read(); outputfile.write(ByteRead); } 21
  22. 22. Program: Copy Byte while(ByteRead!=-1); } catch(FileNotFoundException e) { System.out.println(" File not found"); } catch(IOException e) { System.out.println(" I/O Exception "); } finally { try { inputfile.close(); outputfile.close(); } catch(IOException e) { } 22
  23. 23. Algorithm For Count Char:  Step 1: Start  Step2: Create file stream i..  Step3: Open Input.txt.  Step4: Read and write file.  Step5:close. 23
  24. 24. Program: Count Char File InFile = new File("Input.txt"); int count=0; FileReader inp = null; // creates file stream i try { inp=new FileReader(InFile); // opens infile.dat // read and write file int cho; 24
  25. 25. Program: Count char while((cho=inp.read())!=-1) { if((cho!=' ') && (cho>=65 && cho<=143)) count=count+1; } System.out.println("Total number of characters in files are :"+count); } catch(IOException e) { System.out.println(e); System.exit(-1); } 25
  26. 26. FileReader • The FileReader class creates a Reader that you can use to read the contents of a file. Its two most commonly used constructors are shown here: FileReader(String filePath) FileReader(File fileObj) Either can throw a FileNotFoundException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. • Reader is an abstract class that defines Java’s model of streaming character input. All of the methods in this class will throw an IOException on error conditions. Methods in Reader class are shown on next slide. ALGORITHM:  Step 1: Start  Step2: Give input to a file.  Step3: Create File reader class.  Step4: Read character.  Step5:close. 26
  27. 27. Methods Of File Reader • Method o abstract void close( ) o void mark(int numChars) o boolean markSupported( ) o int read( ) o int read(char buffer[ ]) • Description o Closes the input source. Further read attempts will generate an IOException. o Places a mark at the current point in the input stream that will remain valid until numChars characters are read. o Returns true if mark( )/reset( ) are supported on this stream. o Returns an integer representation of the next available character from the invoking input stream. –1 is returned when the end of the file is encountered. o Attempts to read up to buffer.length characters into buffer and returns the actual number of characters that were successfully read. –1 is returned when the end of the file is encountered. 27
  28. 28. Program:File Reader FileReader fr=new FileReader("Input.txt"); char data1[]=new char[1024]; int charread=fr.read(data1) System.out.println(new String (data1,0,charread)); fr.close(); 28
  29. 29. FILE WRITER • FileWriter creates a Writer that you can use to write to a file. Its most commonly used constructors are shown here: • FileWriter(String filePath) FileWriter(String filePath, boolean append) FileWriter(File fileObj) • FileWriter(File fileObj, boolean append) • They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. If append is true, then output is appended to the end of the file. • Creation of a FileWriter is not dependent on the file already existing. FileWriter will create the file before opening it for output when you create the object. In the case where you attempt to open a read-only file, an IOException will be thrown. ALGORITHM:  Step 1: Start  Step2: Take input from a file.  Step3: Initialize the input.  Step4: Create File writer object.  Step5: Write it into file.  Step6:close. 29
  30. 30. Program: File Writer char data2[]={'r','i','z','v','i',' ','c','o','l','l','e','g','e'}; FileWriter fo=new FileWriter("file8.txt"); for(int i=0;i<data2.length;i++) { fo.write(data2[i]); } FileWriter fu=new FileWriter("file9.txt"); fu.write(data2); FileWriter ft=new FileWriter("file10.txt"); ft.write(data2,2,8); ft.append(" hello there"); fo.close(); fu.close(); ft.close(); 30
  31. 31. INPUTSTREAMREADER: • An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted. • Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation. • For top efficiency, consider wrapping an InputStreamReader within a BufferedReader. • For example: • BufferedReader in = new BufferedReader(newInputStreamReader(System.in)); ALGORITHM:  Step 1: Start  Step2: Give input to a file.  Step3: Create File reader class.  Step4:Print character.  Step5:close. 31
  32. 32. Program:InputStreamReader: int character; InputStreamReader finp=new InputStreamReader(System.in); while((character=finp.read())!=-1) { System.out.println((char)character); } (); 32
  33. 33. Read Write Bytes: • Most often used stream classes are FileInputStream and FileOutputStream, which create byte stream linked to files. • To open file simply create an object of one of these classes, specifying the name of the files as an argument to the constructer. Constructer: FileInputStream(Stringfilename)throws FileNotFoundException FileOutputStream(String filename)throws fileNotfoundException ALGORITHM:  Step 1: Start  Step2: Enter data in a file or from a file.  Step3:Create file output class object.  Step4: Create object file input stream.  Step5:Output can be seen in ("phone.txt").  Step6:close. 33
  34. 34. Program: Read write Byte byte [] name = new byte[LINELENGTH]; byte [] number = new byte[LINELENGTH]; FileOutputStream fos = new FileOutputStream("phone.txt"); while(true) { System.out.println("Enter Name (enter 'exit' to quit): "); readLine(name); if("exit".equalsIgnoreCase(new String(name,0,4))) break; for(int i = 0;name[i] != 13; i++) { fos.write(name[i]); } fos.write('.'); fos.write('.'); fos.write('.'); 34
  35. 35. Program: Read Write Byte System.out.println("Enter Number : "); readLine(number); for( int i = 0; number[i] != 13; i++) { fos.write(number[i]); } fos.write('n'); } fos.close(); FileInputStream fih = new FileInputStream("phone.txt"); int i; System.out.println("n The Telephone Directory:n"); do { i = fih.read(); if( i != -1 ) System.out.print((char)i); }while( i != -1); fih.close(); } catch(Exception e) {} 35
  36. 36. Read Write Character: • The subclasses of Reader and Writer implement streams that can handle character • The two subclasses used for handling characters in files are File Reader(for reading character) and File Writer(for writing character). • The following program uses file streams to copy the contents of a file named “Input.txt” into a file called “Outfile3.txt”. ALGORITHM:  Step 1: Declare and create i/o files.  Step2: Create files stream I and o.  Step3: Open Input.txt and Output3.txt file.  Step4: Read and write file.  Step5: Stop. 36
  37. 37. Program: Read Write Character File InFile2=new File("Input.txt"); File OutFile=new File("Output3.txt"); FileReader inr =null; FileWriter or=null; try { inr=new FileReader(InFile2); or=new FileWriter(OutFile); int ch3; while((ch3=inr.read())!=-1); or.write(ch3); } 37
  38. 38. Program: Read Write Character catch(IOException e) { System.out.println(e); System.exit(-1); } finally { try { inr.close(); or.close(); } catch(IOException e) { } } } 38
  39. 39. Write Bytes: • The subclasses of Reader and Writer implement streams that can handle bytes. • The two subclasses used for handling Bytes in files are FileInputstream and FileOutputStream. • In this program FileOutputStream class is used for writing bytes to a file. • The program writes the names of some cities stored in a byte array to anew named “city.txt”. • We can verify the contents of the file by using the command: type city.txt ALGORITHM:  Step 1: Declare and initialize a byte array.  Step2: Create an output file stream.  Step3: Connect the out file stream to “city.txt”.  Step4: write data to the stream.  Step5: Stop. 39
  40. 40. Program: Write Bytes bytecities[]={'D','E','L','H','I','n','M','A','D','R','A','S','n','L','O','N','D' ,'O','N','n'}; FileOutputStream outfile=null; try { outfile=new FileOutputStream("city.txt"); outfile.write(cities); outfile.close(); } catch(IOException ioe) { System.out.println(ioe); System.exit(-1); } 40
  41. 41. Writing String to a File: • In this program we, write to the file and so we create a new Print Stream object that takes as its constructor to the existing FileOutputSteram. • Any data we send from Print Stream will now be passed to the FileoutputStream, and ultimately to disk. • We can then make a call to the println method, passing it a string, then close the connection. ALGORITHM: • Step1: declare a file output object • Step2: declare a print stream object • Step3: Create a new file output stream • Step4: connected to "myfile.txt". • Step5: Connect print stream to the output stream. • Step6: Stop. 41
  42. 42. Program: Writing String to a File: FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object try { // Create a new file output stream // connected to "myfile.txt" out = new FileOutputStream("myfile.txt"); // Connect print stream to the output stream p = new PrintStream( out ); p.println ("This is written to a file"); p.close(); } catch (Exception e) { System.err.println ("Error writing to file"); } 42
  43. 43. 43
  44. 44. List Of Choice import java.io.*; public class Pro1 { static int LINELENGTH = 80; public static void main(String[] args) throws Exception { try { int ch; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Choice"); System.out.println("1 for Buffered Input Stream"); System.out.println("2 To Append Demo"); System.out.println("3 To CopyBytes"); System.out.println("4 To Count Char"); System.out.println("5 To FileInputStream"); System.out.println("6 to File OutputStream"); System.out.println("7 To FileReader"); System.out.println("8 To File Properties"); System.out.println("9 To File Writter"); System.out.println("10 To Input Stream Reader"); System.out.println("11 To read Write Bytes"); System.out.println("12 To Read Write Character"); System.out.println("13 To Write Bytes"); System.out.println("14 To Write String To File"); ch=Integer.parseInt(br.readLine()); switch (ch) { 44
  45. 45. Output of Choice List 45
  46. 46. Choice 1: Buffered Input Stream case 1: String s = "This is a &copy; copyright symbol " +"but this is &copy not.n"; byte buf[] = s.getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(buf); BufferedInputStream f = new BufferedInputStream(in); int c; boolean marked = false; while ((c = f.read()) != -1) { switch(c) { case '&':if (!marked) { f.mark(32); marked = true; } else { marked = false; } break; 46
  47. 47. case ';':if (marked) { marked = false; System.out.print("(c)"); } else System.out.print((char) c); break; case ' ':if (marked) { marked = false; f.reset(); System.out.print("&"); } else System.out.print((char) c); break; default:if (!marked) System.out.print((char) c); break; } } break; 47
  48. 48. Output of Choice 1 48
  49. 49. Choice 2: Append Demo case 2: RandomAccessFile RA; try { RA = new RandomAccessFile("BookTitle.txt","rw"); RA.seek(RA.length()); // Go to the end RA.writeBytes("Studying Dsf"); // Append data RA.close(); } catch(IOException e) { System.out.println(e); } break; 49
  50. 50. Output of Choice 2 50
  51. 51. Choice 3: Copy Bytes Case 3: // declare input and output file streams FileInputStream inputfile = null; // Input stream FileOutputStream outputfile = null; // Output stream //Declare a variable to hold a byte byte ByteRead; try { // Connect inputfile to file1.text inputfile = new FileInputStream("Input.txt"); // Connect outfile to file2.text outputfile = new FileOutputStream("Output.txt"); // Reading bytes from Input.txt and Writing to Output.txt do { ByteRead =(byte) inputfile.read(); outputfile.write(ByteRead); } while(ByteRead!=-1); } 51
  52. 52. catch(FileNotFoundException e) { System.out.println(" File not found"); } catch(IOException e) { System.out.println(" I/O Exception "); } finally { try { inputfile.close(); outputfile.close(); } catch(IOException e) { } } break; 52
  53. 53. Output of Choice 3 53
  54. 54. Choice 4: To Count Char Case 4: File InFile = new File("Input.txt"); int count=0; FileReader inp = null; // creates file stream i try { inp=new FileReader(InFile); // opens infile.dat // read and write file int cho; while((cho=inp.read())!=-1) { if((cho!=' ') && (cho>=65 && cho<=143)) count=count+1; } System.out.println("Total number of characters in files are :"+count); } catch(IOException e) { System.out.println(e); System.exit(-1); } break; 54
  55. 55. Ouput of Choice 4 55
  56. 56. Choice 5: File Input Stream Case 5: int size; FileInputStream f1=new FileInputStream("Input.txt"); System.out.println("nnn"); System.out.println("Available bytes : " + (size=f1.available())); System.out.println("Reading 50 Bytes.........."); byte bytearray[]=new byte[50]; if(f1.read(bytearray)!=50) { System.out.println("could not get 50 bytes"); } System.out.println(new String(bytearray,0,50)); System.out.println("skipping 50 bytes..........."); f1.skip(50); System.out.println("Reading 50 bytes........"); if(f1.read(bytearray)!=50) { System.out.println("could not get 50 bytes"); } System.out.println(new String(bytearray,0,30)); f1.close(); break; 56
  57. 57. Output of Choice 5: 57
  58. 58. Choice 6:File Output Stream Case 6: byte data[]="This is a string of text.".getBytes(); FileOutputStream fin=new FileOutputStream("Output.txt"); for(int i=0;i<data.length;i++) { fin.write(data[i]); } FileOutputStream f2=new FileOutputStream("Output2.txt"); f2.write(data); FileOutputStream f3=new FileOutputStream("Output3.txt"); f3.write(data,5,10); fin.close(); f2.close(); f3.close(); break; 58
  59. 59. Output of Choice 6: 59
  60. 60. Choice 7: File Reader case 7: FileReader fr=new FileReader("Input.txt"); char data1[]=new char[1024]; int charread=fr.read(data1); System.out.println(new String (data1,0,charread)); fr.close(); break; 60
  61. 61. Output of Choice 7 61
  62. 62. Choice 8: File Properties case 8: File fis=new File("Input.txt"); System.out.println("File Name is "+fis.getName()); System.out.println("n"); System.out.println(fis.isFile() ? "Is File" : "Is Directory"); System.out.println("n"); System.out.println("File Size: "+fis.length()); System.out.println("n"); System.out.println("Path: "+ fis.getPath()); System.out.println("n"); System.out.println("Absolute path: "+fis.getAbsolutePath()); System.out.println("n"); System.out.println("File Last modified: "+fis.lastModified()); System.out.println("n"); System.out.println(fis.canRead() ? "File Can Read" : "File Cannot be Read"); System.out.println("n"); System.out.println(fis.canWrite() ? "File Can Write" : "File Cannot Be Written"); break; 62
  63. 63. Output of Choice 8 63
  64. 64. Choice 9: File Writer case 9: char data2[]={'r','i','z','v','i',' ','c','o','l','l','e','g','e'}; FileWriter fo=new FileWriter("file8.txt"); for(int i=0;i<data2.length;i++) { fo.write(data2[i]); } FileWriter fu=new FileWriter("file9.txt"); fu.write(data2); FileWriter ft=new FileWriter("file10.txt"); ft.write(data2,2,8); ft.append(" hello there"); fo.close(); fu.close(); ft.close(); break; 64
  65. 65. Output of Choice 9 65
  66. 66. Choice 10: Input Stream Reader case 10: int character; InputStreamReader finp=new InputStreamReader(System.in); while((character=finp.read())!=-1) { System.out.println((char)character); } break; 66
  67. 67. Output of Choice 10 67
  68. 68. Choice 11: Read Write Bytes case 11: try { byte [] name = new byte[LINELENGTH]; byte [] number = new byte[LINELENGTH]; FileOutputStream fos = new FileOutputStream("phone.txt"); while(true) { System.out.println("Enter Name (enter 'exit' to quit): "); readLine(name); if("exit".equalsIgnoreCase(new String(name,0,4))) break; for(int i = 0;name[i] != 13; i++) { fos.write(name[i]); } fos.write('.'); fos.write('.'); fos.write('.'); 68
  69. 69. System.out.println("Enter Number : "); readLine(number); for( int i = 0; number[i] != 13; i++) { fos.write(number[i]); } fos.write('n'); } fos.close(); FileInputStream fih = new FileInputStream("phone.txt"); int i; System.out.println("n The Telephone Directory:n"); do { i = fih.read(); if( i != -1 ) System.out.print((char)i); }while( i != -1); fih.close(); } catch(Exception e) {} break; 69
  70. 70. private static void readLine(byte [] line) throws IOException { int i = 0, b = 0; while(i < LINELENGTH - 1 && (b = System.in.read()) != 'n') { line[i++] = (byte)b; } } 70
  71. 71. Output of Choice 11 71
  72. 72. Choice 12: Read Write Character case 12: File InFile2=new File("Input.txt"); File OutFile=new File("Output3.txt"); FileReader inr =null; FileWriter or=null; try { inr=new FileReader(InFile2); or=new FileWriter(OutFile); int ch3; while((ch3=inr.read())!=-1); or.write(ch3); } catch(IOException e) { System.out.println(e); System.exit(-1); } 72
  73. 73. finally { try { inr.close(); or.close(); } catch(IOException e) { } } break; 73
  74. 74. Output of Choice 12 74
  75. 75. Choice 13: Write Bytes case 13: byte cities[]={'D','E','L','H','I','n','M','A','D','R','A','S','n','L','O','N','D','O','N','n'}; FileOutputStream outfile=null; try { outfile=new FileOutputStream("city.txt"); outfile.write(cities); outfile.close(); } catch(IOException ioe) { System.out.println(ioe); System.exit(-1); } break; 75
  76. 76. Output of Choice 13: 76
  77. 77. Choice 14: Write String To File case 14: FileOutputStream out; PrintStream p; try { out = new FileOutputStream("myfile.txt"); p = new PrintStream( out ); p.println ("This is written to a file"); p.close(); } catch (Exception e) { System.err.println ("Error writing to file"); } break; } } catch(Exception e) {} } } } 77
  78. 78. Output of Choice 14 78
  79. 79. Bibliography: Websites: www.google.com www.wikipedia.com www.sourcecode.com Books: Programming in Java by Balguruswamy. Data Structures and files by Bakti. 79
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×