Topic: Sorting Arrays and Reading Files Part 2 Create a ReadFile class that read
ID: 3743551 • Letter: T
Question
Topic: Sorting Arrays and Reading Files
Part 2 Create a ReadFile class that reads in a file We are golng to continue exploring handling binary data In java. You will wrte a dass that reads in a fle with a specific format The file has the following format: e An integer, the number of bytes in the String * A byte, the encoding of the String. 0 1 means the String s encoded using StandardCharsets. US ASCII o 2 means the String s encoded using StandardCharsets UTF-16LE o 3 means the String is encoded using StandardCharsets.UTF 8 o 4 means the String is encoded using StandardCharsets. UTF 16 *The bytes that make up the StringExplanation / Answer
Given below is the code for the question. Please use it with your test data files and ReadFileTest class provided by instructor
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Please do rate the answer if it was helpful. Thank you
IReadFile.java
---------
import java.io.IOException;
public interface IReadFile {
String readFile(String fileName) throws IOException;
}
ReadFile.java
----------
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class ReadFile implements IReadFile{
@Override
public String readFile(String fileName) throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream(fileName));
int numBytes = dis.readInt();
byte dataType = dis.readByte();
byte[] data = new byte[numBytes];
String value = "";
dis.read(data);
if(dataType == 1)
value = new String(data, StandardCharsets.US_ASCII);
else if(dataType == 2)
value = new String(data, StandardCharsets.UTF_16LE);
else if(dataType == 3)
value = new String(data, StandardCharsets.UTF_8);
else if(dataType == 4)
value = new String(data, StandardCharsets.UTF_16);
dis.close();
return value;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.