Anda di halaman 1dari 13

Files And Streams

Files and Stream


a. Using the Files Class
b. Random Access Files
c. Stream
d. Byte and character Stream
e. Buffered Reader

Using The FILE Class


Use

theFileclass
for
typical
operations such as copying, moving,
renaming,
creating,
opening,
deleting, and appending to files. You
can also use theFileclass to get and
set file attributes orDate Time
information related to the creation,
access, and writing of a file.

Random Access Files


random access files as their name

implies, once they are opened, they


can be read from or written to in a
random manner just by using a
record number or you can add to the
end since you will know how many
records are in the file.

STREAMS
Streamis the abstract base class of all

streams. A stream is an abstraction of a


sequence of bytes, such as a file, an
input/output
device,
an
inter-process
communication pipe, or a TCP/IP socket.
TheStreamclass and its derived classes
provide a generic view of these different
types of input and output, isolating the
programmer from the specific details of the
operating system and the underlying
devices.

three fundamental operations


1.You can read from streams. Reading is the

transfer of data from a stream into a data


structure, such as an array of bytes.
2.You can write to streams. Writing is the transfer
of data from a data structure into a stream.
3.Streams can support seeking. Seeking is the
querying and modifying of the current position
within a stream. Seek

Byte and Character


Streams
Character streamsare intended exclusively

for
character
data.Byte
streamsare
intended for general purpose input and
output. Of course, fundamentally all data
consist of patterns of bits grouped into 8-bit
bytes. So, logically all streams could be
called "byte streams". However streams that
are intended for bytes that represent
characters are called "character streams"
and all others are called "byte streams".

Buffered Streams
Buffered

Streamcan be composed
around certain types of streams. It
provides implementations for reading and
writing bytes to an underlying data source
or repository. Use Binary Reader andBinary
Writer for reading and writing other data
types.

import java.io.*;
public class CopyFile{
private static void copyfile(String srFile, String

dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

catch(FileNotFoundException ex){

System.out.println(ex.getMessage() + " in
the specified directory.");

System.exit(0);

//For Append the file.

catch(IOException e){

System.out.println(e.getMessage());

//For Overwrite the file.

OutputStream out = new FileOutputStream(f2);

public static void main(String[] args){

// OutputStream out = new

FileOutputStream(f2,true);

byte[] buf = new byte[1024];

copyfile("c:\\out.txt","d:\\kulafu.edi");

out.write(buf, 0, len);

int len;
while ((len = in.read(buf)) > 0){

in.close();
out.close();
System.out.println("File copied.");
}

import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new
FileWriter("out.txt");
BufferedWriter out = new
BufferedWriter(fstream);
out.write("pink");
//Close the output stream
out.close();
}catch (Exception e){//Catch
exception if any
System.err.println("Error: " +
e.getMessage());
}
}
}

import java.io.*;
public class ReadAccessFile{
public static void main(String[]
args) throws IOException{
BufferedReader in = new
BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter File name
: ");
String str = in.readLine();
File file = new File(str);
if(!file.exists())
{
System.out.println("File does not
exist.");
System.exit(0);
}

public

class Server

static void Main()


{
// This is a Windows Sockets 2 error code.
const int WSAETIMEDOUT = 10060;

Socket serverSocket;
int bytesReceived, totalReceived = 0;
byte[] receivedData = new byte[2000000];

// Create random data to send to the client.


byte[] dataToSend = new byte[2000000];
new Random().NextBytes(dataToSend);

try
{

// Send data to the client.

Console.Write("Sending data ... ");

int bytesSent = serverSocket.Send(


dataToSend, 0, dataToSend.Length, SocketFlags.None);

Console.WriteLine("{0} bytes sent.\n",

bytesSent.ToString());

// Set the timeout for receiving data to 2 seconds.

serverSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 2000);

// Receive data from the client.

Console.Write("Receiving data ... ");

try

do

{
bytesReceived = serverSocket.Receive(receivedData,

0, receivedData.Length, SocketFlags.None);

totalReceived += bytesReceived;

IPAddress ipAddress =
Dns.Resolve(Dns.GetHostName()).AddressList[0];

IPEndPoint ipEndpoint = new IPEndPoint(ipAddress,


1800);

// Create a socket and listen for incoming connections.


using(Socket listenSocket = new Socket(
AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp))
{
listenSocket.Bind(ipEndpoint);
listenSocket.Listen(1);
// Accept a connection and create a socket to handle it.
serverSocket = listenSocket.Accept();
Console.WriteLine("Server is connected.\n");

while(bytesReceived != 0);

catch(SocketException e)

if(e.ErrorCode == WSAETIMEDOUT)

{
// Data was not received within the given time.

// Assume that the transmission has ended.

else

{
Console.WriteLine("{0}: {1}\n",

e.GetType().Name, e.Message);

finally

{
Console.WriteLine("{0} bytes received.\n",

totalReceived.ToString());

finally

serverSocket.Shutdown(SocketShutdown.Both);

Console.WriteLine("Connection shut down.");


serverSocket.Close();

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}

Anda mungkin juga menyukai