QA's approach 2 Java - File Handling -FileInputStream & FileOutputStream Examples
File Handling - Learn through Examples
To have an insights into File Handling theory, follow the link - File Handling Theory
Byte Stream implementation examples:
Example1. Read Data from file & write to another file using FileInputStream & FileOutputStream
The flow of Data in this example is structured as follows:
Create a package as follows with Input.txt, Output.txt & CopyBytes Class file
We are going to
Read data from Input.txt to Input Stream & then to CopyBytes.java
Write data from CopyBytes.java to Output Stream & then to Output.txt file
The below is the Execution logic file - > CopyBytes Class file
package fileHandling;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
String sourcePath = "C:/Users/user/workspace/New folder/javaForQA/src/fileHandling/Input.txt";
String desctinationPath = "C:/Users/user/workspace/New folder/javaForQA/src/fileHandling/Output.txt";
File sourceFile = null;
try {
// Open Connection of input stream to Input.txt [Source]
sourceFile = new File(sourcePath);
in = new FileInputStream("sourceFile");
// Open Connection of Output stream to Output.txt [Destination]
out = new FileOutputStream("desctinationPath");
int c;
// read data to input stream from Input.txt & then to Program variable 'c'
while ((c = in.read()) != -1) {
// Write the data read from input stream to C to Output stream
// to Output.txt
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Open Input.txt & write some Text "Input Stream Test Data" & save it.
Shift+Alt+x, J
Comments
Post a Comment