In this assignment, you will write two Java programs, TextToBin and BinToText th
ID: 3717065 • Letter: I
Question
In this assignment, you will write two Java programs, TextToBin and BinToText that covert a file containing integers between text format and binary format. For example,
java TextToBin scores.txt data.sav
java BinToText data.sav recovered.txt
The first command should read a text file named “scores.txt” and convert it to a binary file “data.sav”; the second command should read a binary file called “data.sav” containing integers in binary format and convert it to a text file “recovered.txt”. “scores.txt” and “recovered.txt” should be files containing same numbers.
Your original file and the recovered file are not necessarily identical, as far as they contain the same set of integers. The next two files can be regarded as same.
12 78 56 677 4343 2
23 5 65 165
5465 65 88 465
12 78 56 677
4343 2
23 5 65 165
5465 65 88
465
Requirement for each program:
1. Construct the right stream for input/out.
2. Use correct method to read and write.
Additional requirement:
The original file and the recovered file must have the same numbers in same order.
12 78 56 677 4343 2
23 5 65 165
5465 65 88 465
Explanation / Answer
/*
just create the all files in a proper names as given in the question
> create scores.txt” in the same directory where you run the program
> use the same name data.sav and recovered.txt”.
*/
import java.io.*;
public class TexttoBinary {
public static String ReadFile(String file) throws IOException {
BufferedReader in = null;
String data ;//= in.readLine();
String t="";
try {
in = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
while ((data = in.readLine()) != null) {
t+=data+" ";
System.out.println(data);
}
System.out.println(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return t;
}
public static void WriteFile_text_2_binary(String filename, String file) throws IOException
{
String FILENAME = filename;
DataOutputStream os = new DataOutputStream(new FileOutputStream(FILENAME));
os.writeChars(file);
os.close();
}
public static void WriteFile_binary_2_text(String file,String filename) throws IOException
{
String FILENAME = filename;
DataOutputStream os = new DataOutputStream(new FileOutputStream(FILENAME));
os.writeChars(file);
os.close();
}
public static String B2T(String filename) throws IOException{
DataInputStream input=null;
String b2t="";
try{
input = new DataInputStream(new FileInputStream(filename));
}catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try{
char c;
while ( input.available() > 0 && ((c = input.readChar()) != -1)){
b2t += c;
System.out.print(c);
}
}catch (IOException e) {
e.printStackTrace();
}finally{
input.close();
}
return b2t;
}
public static void main(String[] args) throws IOException {
WriteFile_text_2_binary("data.sav", ReadFile("scores.txt"));
WriteFile_binary_2_text(B2T("data.sav"),"recovered.txt");
}
}