It Assistors
It Assistors

Reputation: 23

read FIile content as bytes java

I have 2 java classes. Let them be class A and class B.

Class A gets String input from user and stores the input as byte into the FILE, then Class B should read the file and display the Byte as String.

CLASS A:

File file = new File("C:\\FILE.txt");

file.createNewFile();

FileOutputStream fos = new FileOutputStream(file);
String fwrite = user_input_1+"\n"+user_input_2;
fos.write(fwrite.getBytes());
fos.flush();
fos.close();

In CLASS B, I wrote the code to read the file, but I don't know how to read the file content as bytes.

CLASS B:

fr = new FileReader(file);
br = new BufferedReader(fr);
arr = new ArrayList<String>();
int i = 0;

while((getF = br.readLine()) != null){  
    arr.add(getF);
}
String[] sarr = (String[]) arr.toArray(new String[0]);

The FILE.txt has the following lines

[B@3ce76a1

[B@36245605

I want both these lines to be converted into their respective string values and then display it. How to do it?

Upvotes: 1

Views: 78

Answers (2)

Oleg Muravskiy
Oleg Muravskiy

Reputation: 775

Since you are writing a byte array through the FileOutputStream, the opposite operation would be to read the file using the FileInputStream, and construct the String from the byte array:

File file = new File("C:\\FILE.txt");
Long fileLength = file.length();
byte[] bytes = new byte[fileLength.intValue()]
try (FileInputStream fis = new FileInputStream(file)) {
    fis.read(bytes);
}
String result = new String(bytes);

However, there are better ways of writing the String to a file.

You could write it using the FileWriter, and read using FileReader (possibly wrapping them by the corresponding BufferedReader/Writer), this will avoid creating intermediate byte array. Or better yet, use Apache Commons' IOUtils or Google's Guava libraries.

Upvotes: 1

widavies
widavies

Reputation: 976

Are you forced to save using a String byte[] representation to save data? Take a look at object serialization (Object Serialization Tutorial), you don't have to worry about any low level line by line read or write methods.

Upvotes: 1

Related Questions