Exercise
Extract text from a binary file
Objetive
Create a program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The extracted characters should be those whose ASCII code is between 32 and 127, or equal to 10 or 13.
Example Code
import java.util.*;
public class Main
{
public static void main(String[] args)
{
java.io.FileInputStream file;
String name;
System.out.println("Enter the file name: ");
name = new Scanner(System.in).nextLine();
if (!(new java.io.File(name)).isFile())
{
System.out.printf("File %1$s not found!" + "\r\n", name);
}
else
{
try
{
file = File.OpenRead(name);
byte[] bytesFile = new byte[file.getLength()];
file.read(bytesFile, 0, (int)file.getLength());
file.close();
java.io.OutputStreamWriter newFile = new java.io.OutputStreamWriter(name + "01.txt");
for (int i = 0; i < bytesFile.length; i++)
{
if (((int)bytesFile[i] >= 32) && ((int)bytesFile[i] <= 127) || ((int)bytesFile[i] == 10) || ((int)bytesFile[i] == 13))
{
newFile.write(String.valueOf((char)bytesFile[i]));
}
}
newFile.close();
}
catch (RuntimeException e)
{
System.out.println("Error, " + e.getMessage());
}
}
}
}