I've used this topic: File to byte[] in Java
Here is my code:
try {
Path path1 = Paths.get(path + fileName);
byte[] fileAsByte = Files.readAllBytes(path1);
System.out.println("Byte : " + fileAsByte.toString());
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
} catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
} catch (OutOfMemoryError e3) {
System.out.println("Out of Memory");
e3.printStackTrace();
}
This code is not triggering any exception, but the output is still:
Byte : [B#60f17a2f
Which seems pretty invalid to me. I'm pretty sure I did a dumb error, but it's been three hours that I've been trying to resolve it, and I could use some fresh eyes on it.
Thanks.
You can't convert an array directly to String and have it readable by the human eye. It is printing out [ (meaning "array"), then B (for byte), then # and its identity hash code.
To get a list of the bytes in the array, use the static Arrays.toString() method instead:
System.out.println("Byte : " + java.util.Arrays.toString(fileAsByte));
(If the bytes represent characters for an output string, use #iTech's solution.)
You should create a String instance initialized with your byte[], e.g.
System.out.println("Byte : " + new String(fileAsByte));
You can also specify the encoding e.g. new String(fileAsBytes,"UTF-8");
Related
Is there a way I can drag and drop csv files containing a (image encoded base64 text) to a jar file and and then get the decoded result in jpg in the directory?
i am trying to understand the logic but i cant find any good refrences online
i would be extremely grateful if someone could teach me
here is the decoding code ive been using
public static void decoder(String base64Image, String pathFile) {
try (FileOutputStream imageOutFile = new FileOutputStream(pathFile)) {
// Converting a Base64 String into Image byte array
byte[] imageByteArray = Base64.getDecoder().decode(base64Image);
imageOutFile.write(imageByteArray);
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
}
I have read other questions similar to this but didn't help much. So I have some serialized content in a file and I am trying to read it and print it on the console, content is getting printed fine but at the end, it's showing an EOFException. Is there any way to fix my code to avoid this exception?
try {
File file = new File("EnrolledStudentsSerial.txt");
FileInputStream fi = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fi);
while(true) {
System.out.println(input.readObject());
}
}
catch (IOException | ClassNotFoundException e) {
System.out.println("Error: " + e);
}
I don't think you want to 'avoid' this exception.
You need to know when you come to the end of the input, and the EOFException is what is telling you you've come to the end of the input.
Rather, you want to stop treating it as an error condition, since it is not an error, it is normal and expected.
try {
… code as before …
}
catch (EOFException e) {
// end of input, nothing to do here
}
catch (IOException | ClassNotFoundException e) {
System.out.println("Error: " + e);
}
I have a string and want to persist it into a file and be able to retrieve it again into a String.
Something is wrong with my code because It's supposing that I must write something binary non readable but when i Open the file I can read this:
Original string:
[{"name":"asdasd","etName":"111","members":[]}]
Stored string in binary file:
[ { " n a m e " : " a s d a s d " , " e t N a m e " : " 1 1 1 " , " m e m b e r s " : [ ] } ]
I detect two problems:
Is not stored in binary! I can read it. It's supposed to be a confused binary text unreadable but I can read it.
When i retrieve it it's being retrieved with that strange space between the characters. So it doesn't works.
This is my code for storing the string:
public static void storeStringInBinary(String string, String path) {
DataOutputStream os = null;
try {
os = new DataOutputStream(new FileOutputStream(path));
os.writeChars(string);
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
And this is my code for reading it from binary to a String:
public static String retrieveStringFromBinary(String file) {
String string = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e){
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return string;
}
Firstly, there isn't really a distinction between a text file and a binary file. A text file is just a file who's content falls in the range of byte values that correspond to characters.
If you want to encrypt the content of the file so it is unreadable just by catting the file then you will need to choose an appropriate encryption method.
Secondly Mixing Readers/Writers and Streams in Java is never a good idea, pick one style and stick to it.
The problem with your function that saves the string to a file is that you are using the writeChars() method, which from the doc does the following:
Writes a char to the underlying output stream as a 2-byte value, high byte first. If no exception is thrown, the counter written is incremented by 2.
Since your string is made up of single byte characters this is leading to the padding of your string with null bytes, which are being converted to spaces when read back in. If you change this to writeBytes() then you should get output without the extra null byte.
The null byte will also stop your read function working as the readLine() function will return null on it's first call due to the leading 0x00 in the file.
Try this out:
public static void storeStringInBinary(String string, String path) {
try(ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(path))) {
os.writeObject(string);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String retrieveStringFromBinary(String file) {
String string = null;
try (ObjectInputStream reader = new ObjectInputStream(new FileInputStream(file))){
string = (String) reader.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return string;
}
System.out.println("======================================");
System.out.println("List of Ships and their revenue");
System.out.println("======================================");
try
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
}
catch (Exception e)
{
System.out.println("Problem");
}
try
{
while (true)
{
Ship copyObject = (Ship)inputStream.readObject();
System.out.println(copyObject.getShipName() + " " + copyObject.getRevenue());// fix format later
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
}
I want to retrieve data from a binary file, which I definitely know that I has data as a objects. But the result of the program is only the below:
=================================
List of Ships and their revenue
=================================
It probably means that there is something wrong with the try block. Note that this is just part of my program, which relates to the result I want to get. Ship is a superclass of the classes to which the object in the file belong. (update: I just print the exception, but no exception is thrown).
By the looks of it you are in an infinite loop which dies with an exception which results in no output. Try doing the following instead of the giant second try catch block.
while(true) {
try{
Ship copyObject = (Ship)inputStream.readObject();
System.out.println(copyObject.getShipName() + " " + copyObject.getRevenue());
}
catch(Exception ex) {
System.out.println("No more ships");
break;
}
}
I am running a Java program that parses BufferedReader input into a delimited string for output to a file. After successfully reading 24 lines from the source file and saving them to the destination file, I get an error message of 3 (using the getMessage()) method in the catch paired with the "read the next line of the file" try.
When I change the catch to the following,
catch (Exception e)
{
System.err.println("Error: " + e.getMessage().getClass().getName());
}
the catch results in the Error: java.lang.String being returned...but no further explanation. Bad characters in the file? Inorrect casting? OutOfBounds as another comment suggested? any other ideas how to extract further information from this error?
I have reviewed the input file in a hex editor and there are no unexpected EOF or null characters between the rows, the input data displays as expected in a hex or text editor, and I cannot find any documentation about how to interpret a 3 error message, or even how to determine if it's an OS or Java exception.
Instead of using e.getMessage(), try using e.printStackTrace(). This will show the full details of the exception and should point you in the right direction.
catch (Exception e)
{
System.err.print("Error: ");
e.printStackTrace();
}
You can also try:
catch (Exception e)
{
System.err.println("Error: " + e);
}