This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and FileOutputStream is used to write to the destination.
public class BStream {
public static void main(String[] args) throws IOException {
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;
try {
sourceStream = new FileInputStream("sorcefile.txt");
targetStream = new FileOutputStream("targetfile.txt");
// Reading source file and writing content to target file byte by byte
int temp;
while ((temp = sourceStream.read()) != -1)
targetStream.write((byte)temp);
}
finally {
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
}
}
}
| Class | Description |
|---|---|
| BufferedInputStream | It is used for Buffered Input Stream. |
| DataInputStream | It contains method for reading java standard datatypes. |
| FileInputStream | This is used to reads from a file. |
| InputStream | This is an abstract class that describes stream input. |
| PrintStream | This contains the most used print() and println() method. |
| BufferedOutputStream | This is used for Buffered Output Stream. |
| DataOutputStream | This contains method for writing java standard data types. |
| FileOutputStream | This is used to write to a file. |
| OutputStream | This is an abstract class that describe stream output. |
In Java, characters are stored using Unicode conventions. Character stream automatically allows us to read/write data character by character. Though it has many classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are character streams used to read from the source and write to the destination respectively.
public class Geeks {
public static void main(String[] args) throws IOException {
FileReader sourceStream = null;
try {
sourceStream = new FileReader("test.txt");
// Reading sourcefile and writing content character by character
int temp;
while ((temp = sourceStream.read()) != -1)
System.out.println((char)temp);
}
finally {
// Closing stream as no longer in use
if (sourceStream != null)
sourceStream.close();
}
}
}
| Class | Description |
|---|---|
| BufferedReader | It is used to handle buffered input stream. |
| FileReader | This is an input stream that reads from file. |
| InputStreamReader | This input stream is used to translate byte to character. |
| OutputStreamReader | This output stream is used to translate character to byte. |
| Reader | This is an abstract class that define character stream input. |
| PrintWriter | This contains the most used print() and println() method. |
| Writer | This is an abstract class that define character stream output. |
| BufferedWriter | This is used to handle buffered output stream. |
| FileWriter | This is used to output stream that writes to file. |
Some of the implementations of Reader classes in Java are mentioned below:
public class Geeks {
public static void main(String[] args) throws IOException {
// Open a file reader
Reader r = new FileReader("file.txt");
PrintStream out = System.out;
// Create a character array and CharBuffer
char[] buffer = new char[10];
CharBuffer charBuffer = CharBuffer.wrap(buffer);
// Check if the reader supports marking
if (r.markSupported()) {
r.mark(100); // Mark the current position
out.println("mark method is supported");
}
// Skip 5 characters in the stream
r.skip(5);
// Check if the stream is ready to read
if (r.ready()) {
// Read 10 characters into the buffer
r.read(buffer, 0, 10);
out.println("Buffer after reading 10 chars: " + Arrays.toString(buffer));
// Read characters into the CharBuffer
r.read(charBuffer);
out.println("CharBuffer contents: " + Arrays.toString(charBuffer.array()));
// Read a single character
out.println("Next character: " + (char)r.read());
}
// Close the reader
r.close();
}
}
Java writer class is an abstract class in the java.io package. It is designed for writing character streams. Writer class in Java provides methods for writing characters, arrays of characters, and strings. Since it is an abstract class, we cannot create an instance of it directly. Instead, we will use one of its concrete subclasses such as FileWriter, BufferedWriter, or PrintWriter.
public class Main {
public static void main(String[] args) throws IOException {
// Writer to output to the console
Writer w = new PrintWriter(System.out);
System.out.println("Example 1: append(char)");
// Appending Characters
w.append('G');
w.append('e');
w.append('e');
w.append('k');
w.append('s');
w.flush();
System.out.println();
System.out.println("Example 2: append(CharSequence)");
CharSequence t = "Hello, Geeks!";
// Appending entire CharSequence
w.append(t);
w.flush();
System.out.println();
System.out.println("Example 3: append(CharSequence, start, end)");
// Appending substring "Hello"
w.append(t, 0, 5);
w.append(" ");
// Appending substring "Geeks"
w.append(t, 7, 12);
w.flush();
System.out.println();
// Close the writer
w.close();
}
}
// Enter data using BufferReader
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
// Reading data using readLine
String s = r.readLine();
Scanner s = new Scanner(System.in);
String s1 = s.nextLine();
public static void main(String[] args) {
// check if length of args array is greater than 0
if (args.length > 0) {
System.out.println("The command line arguments are:");
// iterating the args array and printing the command line arguments
for (String val : args)
System.out.println(val);
}
else
System.out.println("No command line arguments found.");
}
C:\Users\GFG0574\IdeaProjects\Codes\src>java Main Hello world Current working directory: C:\Users\GFG0574\IdeaProjects\Codes\src The command line arguments are: Hello world C:\Users\GFG0574\IdeaProjects\Codes\src>
DataInputStream r = new DataInputStream(System.in);
// Reading integers
System.out.print("Enter an integer: ");
int i = Integer.parseInt(r.readLine());
| Aspect | Scanner | BufferedReader |
|---|---|---|
| Package | It is a part of java.util package. | It is a part of java.io package. |
| Key use | Simple parsing of primitive types and strings | High-performance text reading |
| Performance | Performance is slower due to parsing overhead and tokenization | Performance is faster due to efficient buffering |
| Buffer Size | Buffer Size is smaller | Buffer Size is larger |
| Thread-safe | It is not thread-safe | It is thread-safe |
| Error Handling | Throws Exception like InputMismatchException | Throws Exception like IOException |
public class CreateFile {
public static void main(String[] args) {
try {
File Obj = new File("myfile.txt");
// Creating File
if (Obj.createNewFile()) {
System.out.println("File created: " + Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
public class DeleteFile {
public static void main(String[] args) {
File Obj = new File("myfile.txt");
// Deleting File
if (Obj.delete()) {
System.out.println("The deleted file is : " + Obj.getName());
}
else {
System.out.println("Failed in deleting the file.");
}
}
}
public class CreateFolder {
public static void main(String[] args) {
File folder = new File("myDirectory");
if (!folder.exists()) {
if (folder.mkdir()) {
System.out.println("Folder created successfully!");
} else {
System.out.println("Failed to create folder.");
}
} else {
System.out.println("Folder already exists.");
}
}
}
public class CreateNestedFolders {
public static void main(String[] args) {
File folders = new File("parentDir/childDir");
if (!folders.exists()) {
if (folders.mkdirs()) {
System.out.println("Nested folders created successfully!");
} else {
System.out.println("Failed to create nested folders.");
}
} else {
System.out.println("Folders already exist.");
}
}
}
My simple library
..of useful code