Download Files and Streams

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Files and Streams
• File streams
– Byte-based streams – stores data in binary format
• Binary files – created from byte-based
streams, read by a program that converts data
to human-readable format
– Character-based streams – stores data as a
sequence of characters
• Text files – created from character-based
streams, can be read by text editors
Example : Demonstrating Class File
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class FileDemonstration
{
public static void main( String args[] )throws IOException
{
System.out.print( "Enter file path" );
Scanner input = new Scanner( System.in );
String path =input.nextLine(); //input file path
File name = new File( path );
if ( name.exists() ){
System.out.printf("%s%s\n%s\n%s\n",name.getName()," exists",(
name.isFile() ? "is a file" : "is not a file" ), ( name.isAbsolute() ? "is absolute
path" :"is not absolute path" ), "Last modified: ",name.lastModified(), "Length:
", name.length());
}// end if
} // end main
} // end class
Files Exceptions
• Possible exceptions
– SecurityException – occurs when opening file
using Formatter object, if user does not have
permission to write data to file
– FileNotFoundException – occurs when opening
file using Formatter object, if file cannot be found
and new file cannot be created
– NoSuchElementException – occurs when invalid
input is read in by a Scanner object
– FormatterClosedException – occurs when an
attempt is made to write to a file using an already
closed Formatter object
Creating a Sequential-Access Text File
•
•
•
Java imposes no structure on a file, records do not exist as
part of the Java language.
Records are stored in order by record-key field.
Formatter class can be used to open a text file for writing:
1.
Import the Formatter class
Import java.util.Formatter;
2.
Pass name of file to constructor
Formatter objectname=new Formatter (“path”);
–
–
3.
If file does not exist, will be created
If file already exists, contents are truncated (discarded)
Use method format to write formatted text to file
objectname.format(“formatted text”);
4.
Use method close to close the Formatter object.
objectname.close();
Example :Creating a Sequential-Access Text
File
// This program will read data from user and save it to a file
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;
public class CreateTextFile
{
public static void main( String args[] )throws FileNotFoundException
{
Scanner input = new Scanner( System.in );
Formatter output = new Formatter( "clients.txt" );
while ( input.hasNext() )
{
String str= input.next();
output.format( "%s\r\n",str);
}
output.close();
}
}
Reading Data from a Sequential-Access Text
File
•
•
Data is stored in files so that it may be retrieved for
processing when needed
Scanner object can be used to read data sequentially from
a text file:
1. Pass File object representing file to be read to Scanner
constructor
Scanner objectname=new Scanner(new File(“ path”));
–
2.
FileNotFoundException occurs if file cannot be found
Data read from file using same methods as for
keyboard input – nextInt, nextDouble, next, etc.
objectname.nextInt();or objectname.nextDouble();or objectname.next();
–
3.
IllegalStateException occurs if attempt is made to read
from closed Scanner object
Use method close to close the Scanner object.
objectname.close();
Example :Reading Data From SequentialAccess Text File
// This program will output data from a file to screen
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class CreateTextFile
{
public static void main( String args[] )throws
FileNotFoundException
{
Scanner input2 = new Scanner( new File( "clients.txt" ) );
while ( input2.hasNext() )
{
System.out.println(input2.next());
}
input.close();
}
}
Java Stream
•
•
•
•
•
•
InputStream and OutputStream classes
– abstract classes that declare methods for performing byte-based
input and output
PipedInputStream and PipedOutputStream classes
– Establish pipes between two threads in a program
– Pipes are synchronized communication channels between threads
FilterInputStream and FilterOutputStream classes
– Provides additional functionality to stream, such as aggregating
data byte into meaningful primitive-type units
PrintStream class
– Performs text output to a specified stream
DataInput and DataOutput interfaces
– For reading and writing primitive types to a file
– DataInput implemented by classes RandomAccessFile and
DataInputStream, DataOutput implemented by RandomAccessFile
and DataOuputStream
SequenceInputStream class enables concatenation of several
InputStreams – program sees group as one continuous InputStream
Example : BUFFER ,PRINT AND DATA
STREAM
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedReader;
public class Streamexample
{
public static void main(String[] args)throws IOException
{File inputFile = new File("farrago.txt"); //should be created first
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile); //used file for read data
FileWriter out = new FileWriter(outputFile); //used file for output data
BufferedReader inputStream = new BufferedReader(in);
PrintWriter outputStream = new PrintWriter(out);
String l;
while ((l = inputStream.readLine()) != null) {
System.out.println(l); //writing from buffered stream to screen
outputStream.println(l); //Writing from print stream to file
}
in.close();
out.close();}}