0% found this document useful (0 votes)
3 views

Java2-03Files

The document provides an overview of file handling in Java, including creating, reading, writing, and deleting files and folders. It covers various classes such as File, BufferedReader, BufferedWriter, InputStreamReader, and OutputStreamWriter, along with their methods and examples. The content is structured to guide users through practical implementations of file operations in Java.

Uploaded by

wel24065
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java2-03Files

The document provides an overview of file handling in Java, including creating, reading, writing, and deleting files and folders. It covers various classes such as File, BufferedReader, BufferedWriter, InputStreamReader, and OutputStreamWriter, along with their methods and examples. The content is structured to guide users through practical implementations of file operations in Java.

Uploaded by

wel24065
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Java Files

1
Java Files

22
File handling

3
File handling Cont…

import java.io.File

File myFile = new File(“filename.txt”);

4
File Class Methods

5
Java Create and Write To Files

6
Create a File

7
Getting File Information
import java.io.File;
import java.io.IOException;

Public class GetFileInfo {


public static void main(String[] args) {
File myObj = new File ("c:\\testdata\\myFile.txt");
if (myObj.exists()) {
System.out.println("File name: "+ myObj.getName());
System.out.println("Absolute path: "+myObj.getAbsolutePath());
System.out.println("Writeable: "+myObj.canWrite());
System.out.println("Readable: "+myObj.canRead());
System.out.println("File size in byte "+myObj.length());
}
else
System.out.println("The file does not exits ");
} 8
Delete a File
import java.io.File; // Import the File class

public class DeleteFile {


public static void main(String[] args) {
File myObj = new File(“C:\\Testdata\\test.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}

9
Delete a Folder
You can also delete a folder. However, it must be empty:

import java.io.File;
public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}
10
Write to a File
import java.io.FileWriter;
import java.io.IOException;

Public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter ("c:\\testdata\\myFile.txt");

myWriter.write ("files in java might be tricky, but it is fun enough");


myWriter.close();
System.out.println("successfully wrote to the file");
}
catch (IOException e){
System.out.println("An error occurred");
e.getMessage();
} }}
11
Read a File

12
Listing all files in a Folder

(“c:\\programs\\java”);

13
Java OutputStream / InputStream class

14
BufferedReader

• The BufferedReader maintains an internal buffer of 8192


characters.

• A chunk of characters is read from the disk and stored in


the internal buffer. And from the internal buffer characters
are read individually.

• Hence, the number of communication to the disk is reduced.


This is why reading characters is faster using
BufferedReader .

1515
Create a BufferedReader

In order to create a BufferedReader , we must import the


java.io.BuferedReader package first.

// Creates a FileReader
FileReader file = new FileReader(String file);

// Creates a BufferedReader
BufferedReader buffer = new BufferedReader(file);

// we can specify the size of the internal buffer as well.


BufferedReader buffer = new BufferedReader(file, int size);
1616
Methods of BufferedReader

• read()
- reads a single character from the internal buffer of the reader
• read(char[] array)
- reads the characters from the reader and stores in the specified
array
• read(char[] array, int start, int length)
- reads the number of characters equal to length from the reader
and stores in the specified array starting from the position start

1717
Methods of BufferedReader (Cont…)

• skip()
- To discard and skip the specified number of characters, we
can use the skip() method.

• close() Method
- - To close the buffered reader. Once the close() method is
called, we cannot use the reader to read the data

• ready() - checks if the file reader is ready to be read

1818
BufferedReader Example

package testProject;
import java.io.FileReader;
import java.io.BufferedReader;

public class BufferReaderDemo {


public static void main(String[] args) {
// Creates an array of character
char[] array = new char[100];
try {
// Creates a FileReader
FileReader file = new FileReader("input.txt");
// Creates a BufferedReader
BufferedReader input = new BufferedReader(file);
1919
BufferedReader Example (cont’d)
// Reads characters
input.read(array);
System.out.println("Data in the file: ");
System.out.println(array);
// Closes the reader
input.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.getStackTrace();
}
}
}
2020
More Read Statements
int theCharNum = reader.read();
while(theCharNum != -1) {
char theChar = (char) theCharNum; System.out.print(theChar);
theCharNum = reader.read(); }

• The while loop in the below code will read the file until it
has reached the end of file

while ((line = bufferedReader. readLine ()) != null) {


System.out.println(strCurrentLine);
}

2121
BufferedWriter

• The BufferedWriter maintains an internal buffer of 8192


characters. During the write operation, the characters are
written to the internal buffer instead of the disk. Once the
buffer is filled or the writer is closed, the whole characters
in the buffer are written to the disk.
• Hence, the number of communication to the disk is reduced.
This is why writing characters is faster using BufferedWriter
.

2222
Create a BufferedWriter

// Creates a FileWriter
FileWriter file = new FileWriter(String name);

// Creates a BufferedWriter
BufferedWriter buffer = new BufferedWriter(file);

// Creates a BufferedWriter with specified size internal buffer


BufferedWriter buffer = new BufferedWriter(file, int size);

2323
Methods of BufferedWriter

• write()
▪ writes a single character to the internal buffer of the writer
• write(char[] array)
▪ writes the characters from the specified array to the writer
• write(String data)
▪ writes the specified string to the writer
• Flush()
▪ To clear the internal buffer. This method forces the writer to
write all data present in the buffer to the destination file.

2424
Methods of BufferedWriter (cont’d)

• close()
▪ To close the buffered writer, Once the close() method is
called, we cannot use the writer to write the data.
• newLine()
▪ inserts a new line to the writer
• append()
▪ inserts the specified character to the current writer

2525
BufferedWriter Example

import java.io.FileWriter;
import java.io.BufferedWriter;

public class BufferReaderDemo {


public static void main(String[] args) {
String data = "This is a demo of the flush method";
try {
// Creates a FileWriter
FileWriter file = new FileWriter(" flush.txt");
// Creates a BufferedWriter
BufferedWriter output = new BufferedWriter(file);

2626
BufferedWriter Example (cont’d)
// Writes data to the file
output.write(data);
// Flushes data to the destination
output.flush();
System.out.println("Data is flushed to the file.");
output.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}

2727
More Write Statements

demowrite.write(69); // Printing E
demowrite.newLine(); // inserts a new line
demowrite.write(“Object Programming); // inserts string
demowrite.write(‘B’); // Printing B

String arg = “Java World";


int offset = 5;
demowrite.write(arg,offset,arg.length()-offset);

2828
InputStreamReader class

• The Java InputStreamReader class is often used to read


characters from
• It acts as a bridge between the byte stream to character
stream. Using InputStreamReader, we can read any

2929
Creating an InputStreamReader

• import the InputStreamReader package


java.io.InputStreamReader
• create the input stream reader.
// Creates an InputStream FileInputStream file = new
FileInputStream(String path);
// Creates an InputStreamReader
InputStreamReader input = new InputStreamReader(file);

// Creates an InputStreamReader specifying the character encoding


InputStreamReader input = new InputStreamReader(file, Charset cs);

3030
Methods of InputStreamReader

• read() - reads a single character from the reader


• read(char[] array) - reads the characters from the reader
and stores in the specified array.
• read(char[] array, int start, int length) - reads the number
of characters equal to length from the reader and stores in
the specified array starting from the start
• close() - To close the input stream reader

3131
Reading input.txt file

package testProject;
import java.io.InputStreamReader;
import java.io.FileInputStream;
public class InputStreamReaderDemo {

public static void main(String[] args) {


// Creates an array of character
char[] array = new char[100];
try {
// Creates a FileInputStream
FileInputStream file = new
FileInputStream("input.txt");
// Creates an InputStreamReader
InputStreamReader input = new InputStreamReader(file);
3232
Reading input.txt file (cont’d)
// Reads characters from the file
input.read(array);
System.out.println("Data in the stream:");
System.out.println(array);
// Closes the reader
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}

3333
getEncoding() Method
public static void main(String[] args) {
try {
// Creates a FileInputStream
FileInputStream file = new FileInputStream("input.txt");
// Creates an InputStreamReader with default encoding
InputStreamReader input1 = new InputStreamReader(file);
// Creates an InputStreamReader specifying the encoding
InputStreamReader input2 = new InputStreamReader(file,
Charset.forName("UTF8"));

3434
getEncoding() Method (cont’d)
// Returns the character encoding of the input stream
System.out.println("Character encoding of input1: " +
input1.getEncoding());
System.out.println("Character encoding of input2: " +
input2.getEncoding());
// Closes the reader
input1.close();
input2.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
3535
Other Methods of InputStreamReader

• ready() checks if the stream is ready to be read


• mark() mark the position in stream up to which data has
been read
• reset() returns the control to the point in the stream where
the mark was set

3636
Create an OutputStreamWriter
• // Creates an OutputStream
FileOutputStream file = new FileOutputStream(String path);
• // Creates an OutputStreamWriter
OutputStreamWriter output = new OutputStreamWriter(file);
// Creates an OutputStreamWriter specifying the character encoding
OutputStreamWriter output = new OutputStreamWriter(file,
Charset cs);

3737
Methods of OutputStreamWriter

• write() - writes a single character to the writer


• write(char[] array) - writes the characters from the
specified array to the writer
• write(String data) - writes the specified string to the writer
• flush() - forces to write all the data present in the writer to
the corresponding destination
• append() - inserts the specified character to the current
writer
• getEncoding() - gets the type of encoding that is used to
write data to the output stream.
• close() - To close the output stream writer

3838
OutputStreamWriter Example

public class OutPutStreamWriterDemo1 {


public static void main(String[] args) {

try {
OutputStream outputStream = new
FileOutputStream("output.txt");
Writer outputStreamWriter = new
OutputStreamWriter(outputStream);

outputStreamWriter.write("Hello World");
outputStreamWriter.close();
} catch (Exception e) {
e.getMessage();
}
} } 3939
Another Example
public static void main(String[] args) {
try {
OutputStream outputStream = new
FileOutputStream("myOutput.txt");
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(outputStream, "UTF8");
char[] chars = new char[]{'A','B','C','D','E'};
outputStreamWriter.write(chars);
outputStreamWriter.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
4040

You might also like