FileInputStream to sql.Blob - java

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);

Related

StreamCorruptedException: invalid stream header: 79737200 when reading objects from a file

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)

Issues in scope of variables while using try-catch in Java

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).

Writing,reading and deleting objects into file in java

I want write list of objects into file, and then reading it one by one, and deleting respectively.
Writing and reading functions are below. For one by one reading,first I read all, then pop first, and other write to file again. it very ineffective and takes long time. So, what should I do to get better perfomance? Or maybe, there are other variant to solve this problem
public void writeToDisk(String filePath,TreeMap<String, ArrayList<Integer>> obj){
File file = new File(filePath);
FileOutputStream fout = null;
try {
fout = new FileOutputStream(file);
ObjectOutputStream o = new ObjectOutputStream(fout);
o.writeObject(obj);
o.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public TreeMap<String, ArrayList<Integer>> readFromDisk(String filePath){
TreeMap<String,ArrayList<Integer>> invertIndexMap = null;
File file = new File(filePath);
FileInputStream f;
try {
f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
invertIndexMap = (TreeMap<String, ArrayList<Integer>>) s.readObject();
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return invertIndexMap;
}

How can I convert a byte[] into ArrayList<CustomObjec>?

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

writing arraylist of objects in file

I want to write arraylist of objects in a file. But only one object in going in file.Atfirst I am fetching all the stored objects and then appending new object after that I write whole arrayList to the file.
Here is my code....
public void write(UserDetail u1) throws FileNotFoundException {
ArrayList<UserDetail> al = new ArrayList<UserDetail>();
FileInputStream fin = new FileInputStream(FILEPATH);
try {
if (fin.available() != 0) {
ObjectInputStream ois = new ObjectInputStream(fin);
while (fin.available() != 0 && ois.available() != 0) {
try {
al.add((UserDetail) ois.readObject());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
ois.close();
}
}
}
}
al.add(u1);
FileOutputStream fos = new FileOutputStream(FILEPATH);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(al);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw e;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
help me......thnx in advance
You are reading object of type UserDetail but writing object of type ArrayList. Should probably be:
al = (ArrayList)ois.readObject ();
instead of
al.add ((UserDetail) ois.readObject ());

Categories

Resources