I create a client similarity, where clients register an account (an object is created) which is stored in a file.
Objects are written to the file as required, I override the writeStreamHeader() method. But when I try to read them all, their file throws an exception.
Write the objects to the file here.
public static void saveAccaunt(LoginAndPass gamers) {
boolean b = true;
FileInputStream fis = null;
try{
fis = new FileInputStream("student.ser");
fis.close();
}
catch (FileNotFoundException e)
{
b = false;
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fileOutputStream = new FileOutputStream("student.ser",true);
ObjectOutputStream os = null;
if(b = true){
os = new AppendingObjectOutputStream(fileOutputStream);
System.out.println("Объект добавлен!");
}else {
os = new ObjectOutputStream(fileOutputStream);
System.out.println("Создан");
}
os.writeObject(gamers);
os.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("student.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
test = new ArrayList<>();
while (true){
test.add(objectInputStream.readObject());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(test.get(0));
}
Here is the error log for the exception thrown:
java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
at java.io.ObjectInputStream.(ObjectInputStream.java:358)
at Registratsiya.AllGamers.main(AllGamers.java:48)
Exception in thread "main" java.lang.NullPointerException
at Registratsiya.AllGamers.main(AllGamers.java:61)
I have a class PDF which implements an interface fileReader.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class PDF implements fileReader {
#Override
public byte[] readFile(File pdfDoc) {
if (!pdfDoc.exists()) {
System.out.println("Could not find" + pdfDoc.getName() + " on the specified path");
return null;
}
FileInputStream fin = null;
try {
fin = new FileInputStream(pdfDoc);
} catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
}
byte fileContent[] = new byte[(int) pdfDoc.length()];
try {
fin.read(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
return fileContent;
}
}
import java.io.File;
public interface fileReader {
<T> T readFile(File fileObject);
}
I notice that there are scope issues for variables fin.
Another implementation I made was:
public byte[] readFile1(File pdfDoc) {
if (!pdfDoc.exists()) {
System.out.println("Could not find" + pdfDoc.getName() + " on the specified path");
return null;
}
FileInputStream fin = null;
try {
fin = new FileInputStream(pdfDoc);
byte fileContent[] = new byte[(int) pdfDoc.length()];
try {
fin.read(fileContent);
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
}
return fileContent;
}
But now I could not access fileContent.
How can I combine the try-catches so that I don't have scope problems?
Can there be a better design approach to this problem? I have to make functions for reading three different types of file.
Since Java 7 you can combine the try-catch as follows:
FileInputStream fin = null;
try {
fin = new FileInputStream(pdfDoc);
byte fileContent[] = new byte[(int) pdfDoc.length()];
fin.read(fileContent);
} catch (IOException | FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
}
Which, in my opinion, makes the code cleaner and variable scopes more obvious.
You can nest the try catch statements:
try {
FileInputStream fin = new FileInputStream(pdfDoc);
byte fileContent[] = new byte[(int) pdfDoc.length()];
try {
fin.read(fileContent);
return fileContent;
} catch (IOException e) {
e.printStackTrace();
} finally {
fin.close();
}
} catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
}
return null;
Note that I added a close() in a finally clause to clean up. And also returning null is probably not what you want in case of error, but that's application specific.
You can have one try with multiple catch blocks.
try {
//do stuff
}
catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
You can modify this part:
FileInputStream fin = null;
try {
fin = new FileInputStream(pdfDoc);
} catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
}
byte fileContent[] = new byte[(int) pdfDoc.length()];
try {
fin.read(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
By
{
......
FileInputStream fin = null;
byte fileContent[]=null;
try {
fin = new FileInputStream(pdfDoc);
fileContent = new byte[(int) pdfDoc.length()];
fin.read(fileContent);
} catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return fileContent
}
I would write like this:
public byte[] readFile(File pdfDoc) {
if (!pdfDoc.exists()) {
System.out.println("Could not find" + pdfDoc.getName() + " on the specified path");
return null;
}
FileInputStream fin = null;
byte fileContent[] = new byte[(int) pdfDoc.length()];
try {
fin = new FileInputStream(pdfDoc);
fin.read(fileContent);
} catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fin) {
fin.close();
}
}
return fileContent;
}
Since Java 7, there is a nice utility methods for reading the entire content of a file:
return Files.readAllBytes(pdfFile.toPath());
This method will open and close the FileInputStream for you, so you don't need to do this yourself. It throws an IOException if something goes wrong. Usually, it's best to let this exception propagate to the caller, but if you really want to return null in that case, you can accomplish this as follows:
try {
return Files.readAllBytes(pdfFile.toPath());
} catch (IOException e) {
e.printStackTrace();
return null;
}
This also has the nice advantage that the value returned in that case is explicit - or did you really mean to return an array filled with 0 values if the file could no longer be found, as your current code does?
Note that since NoSuchFileException is a subclass of IOException, the catch block will handle both. If you want to handle it differently you can write a separate catch block for the NoSuchFileException:
try {
return Files.readAllBytes(pdfFile.toPath());
} catch (NoSuchFileException e) {
System.err.println("Oh no, the file has disappeared.");
e.printStackTrace();
return null;
} catch (IOException e) {
System.err.println("The file exists, but could not be read.");
e.printStackTrace();
return null;
}
Finally, I should probably mention that your file reading code is incorrect, as InputStream.read() does not necessarily read the entire file at once. That's why it returns the number of bytes read so you can invoke it again for the rest of the file. But as I said, since Java 7 you don't need to use such low level APIs (unless the file is too big to fit into memory, of course).
I'm trying to upload an image to a database(sql.Blob), but I'm having problems converting objects.
JFileChooser jf = new JFileChooser();
if (jf.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File f = jf.getSelectedFile();
try {
FileInputStream is = new FileInputStream(f);
byte[] cadenaBytes =IOUtils.toByteArray(is);
imagenUser.setBytes(1, cadenaBytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
The problem is that when the last line is executed:
java.lang.NullPointerException
I have a FileInputStream and I need a sql.Blob.
SOLUTION: Swap the last lane to:
imagenUser= new SerialBlob(cadenaBytes);
I have a problem with reading objects from file Java.
file is anarraylist<projet>
This is the code of saving objects :
try {
FileOutputStream fileOut = new FileOutputStream("les projets.txt", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (projet a : file) {
out.writeObject(a);
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
And this is the code of reading objects from file ::
try {
FileInputStream fileIn = new FileInputStream("les projets.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
while (in.available() > 0){
projet c = (projet) in.readObject();
b.add(c);
}
choisir = new JList(b.toArray());
in.close();
} catch (Exception e) {
e.printStackTrace();
}
Writing is working properly. The problem is the reading... it does not read any object (projet) What could be the problem?
As mentioned by EJP in comment and this SO post . if you are planning to write multiple objects in a single file you should write custom ObjectOutputStream , because the while writing second or nth object header information the file will get corrupt.
As suggested by EJP write as ArrayList , since ArrayList is already Serializable you should not have issue. as
out.writeObject(file) and read it back as ArrayList b = (ArrayList) in.readObject();
for some reason if you cant write it as ArrayList. create custome ObjectOutStream as
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
#Override
protected void writeStreamHeader() {}
}
and change your writeObject as
try {
FileOutputStream fileOut= new FileOutputStream("les_projets.txt",true);
MyObjectOutputStream out = new MyObjectOutputStream(fileOut );
for (projet a : file) {
out.writeObject(a);
}
out.close();
}
catch(Exception e)
{e.printStackTrace();
}
and change your readObject as
ObjectInputStream in = null;
try {
FileInputStream fileIn = new FileInputStream("C:\\temp\\les_projets1.txt");
in = new ObjectInputStream(fileIn );
while(true) {
try{
projet c = (projet) in.readObject();
b.add(c);
}catch(EOFException ex){
// end of file case
break;
}
}
}catch (Exception ex){
ex.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I receive a byte[] from my internal storage and now I don't know how to convert it into my ArrayList.
I'm referring to this post. -->>THIS<<--
snipped code:
ArrayList<KFZInfo> toReturn = null;
FileInputStream fis;
try {
fis = openFileInput("kfzList");
ObjectInputStream oi = new ObjectInputStream(fis);
toReturn = (ArrayList<KFZInfo>) oi.readObject();
oi.close();
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
At toReturn = (ArrayList<KFZInfo>) oi.readObject(); it is throwing an error which says: java.lang.ClassCastException: byte[] cannot be cast to java.utio.ArrayList
And thats how I write it on the internal storage:
try {
FileOutputStream fos = openFileOutput("kfzList", Context.MODE_PRIVATE);
ObjectOutputStream oo = new ObjectOutputStream(fos);
oo.writeObject(listKfzInfo.toString().getBytes());
oo.flush();
oo.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
How do I solve this problem?
Change
oo.writeObject(listKfzInfo.toString().getBytes());
with
oo.writeObject(listKfzInfo);
I assuming that listKfzInfo is an ArrayList<KFZInfo> and that KFZInfo implements Serializable and that all fields inside KFZInfo implements Serializable