File Handling in Java
File handling in Java refers to the process of reading from and writing to files in the computer's file system. Java provides a set of classes in the java.io
package to handle file input and output operations.
To read data from a file, you can use the FileInputStream
class. To write data to a file, you can use the FileOutputStream
class. Both classes are used in a similar way, with the difference being that FileInputStream
reads data from a file while FileOutputStream
writes data to a file.
Here is an example of reading data from a file using FileInputStream
:
javaimport java.io.FileInputStream;
import java.io.IOException;
public class ReadFromFileExample {
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("example.txt");
int data;
while ((data = input.read()) != -1) {
System.out.print((char) data);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we create a FileInputStream
object to read data from a file named "example.txt". We then use a while
loop to read data from the file one byte at a time until the end of the file is reached (indicated by the -1
value). The read()
method returns the next byte of data as an integer value, so we cast it to a char
to print it as a character.
Here is an example of writing data to a file using FileOutputStream
:
javaimport java.io.FileOutputStream;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
FileOutputStream output = new FileOutputStream("example.txt");
String data = "Hello, world!";
output.write(data.getBytes());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we create a FileOutputStream
object to write data to a file named "example.txt". We then use the write()
method to write the string "Hello, world!" to the file. Note that we convert the string to a byte array using the getBytes()
method before writing it to the file. Finally, we close the output stream to ensure that all data is written to the file
Comments
Post a Comment