The following source code is an example of how to read and write the content of a file character-by-character to another file. This is also an example of how to give the file name as an input at the command prompt :
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ReadWrite {
public static void main(String[] args)throws IOException {
FileReader fileInput = null;
FileWriter fileOutput = null;
Scanner input;
try
{
System.out.println("Enter the File Name with Location");
input=new Scanner(System.in);
String filePath=input.nextLine();
fileInput = new FileReader(filePath);
fileOutput = new FileWriter("C:\\Untitled1.txt");
int character;
while ((character = fileInput.read()) != -1) {
fileOutput.write(character);
}
}
catch (IOException e)
{
System.out.println("Error message: " + e.getMessage());
}
finally
{
if (fileInput != null)
fileInput.close();
if (fileInput != null)
fileOutput.close();
}
}
}
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ReadWrite {
public static void main(String[] args)throws IOException {
FileReader fileInput = null;
FileWriter fileOutput = null;
Scanner input;
try
{
System.out.println("Enter the File Name with Location");
input=new Scanner(System.in);
String filePath=input.nextLine();
fileInput = new FileReader(filePath);
fileOutput = new FileWriter("C:\\Untitled1.txt");
int character;
while ((character = fileInput.read()) != -1) {
fileOutput.write(character);
}
}
catch (IOException e)
{
System.out.println("Error message: " + e.getMessage());
}
finally
{
if (fileInput != null)
fileInput.close();
if (fileInput != null)
fileOutput.close();
}
}
}
No comments:
Post a Comment