.jpg
, .png
)
.mp3
)
.mp4
)
.exe
)
0
and 1
.
H
β 01001000
InputStream
(for reading bytes)
OutputStream
(for writing bytes)
read()
method is common to all InputStream
classes, and the write()
method is common to all OutputStream
classes. Together, they form the basic building blocks of byte stream I/O in Java.
InputStream
(FileInputStream
):
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFileExample
{
public static void main(String[] args)
{
try
{
// Open file for reading
FileInputStream fis = new FileInputStream("d://aaa.txt");
int i;
System.out.println("----- Reading data from file -----");
while ((i = fis.read()) != -1)
{
System.out.print((char) i); // convert byte to char
}
fis.close();
}
catch (IOException e)
{
System.out.println("Error reading file: " + e.getMessage());
}
}
}
aaa.txt
file in D drive (d://).
OutputStream
(FileOutputStream
):
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample
{
public static void main(String[] args)
{
try
{
// Open file for writing
FileOutputStream fos = new FileOutputStream("d://bbb.txt");
String data = "Hello, this is my first Java Program to write data in file....";
fos.write(data.getBytes()); // write string as bytes
fos.close();
System.out.println("Data successfully written to output.txt");
}
catch (IOException e)
{
System.out.println("Error writing file: " + e.getMessage());
}
}
}
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.