Convert byte[] to ArrayList<String> - java

I found a question here on SO: Convert ArrayList<String> to byte []
It is about converting ArrayList<String> to byte[].
Now is it possible to convert byte[] to ArrayList<String> ?

Looks like nobody read the original question :)
If you used the method from the first answer to serialize each string separately, doing exactly the opposite will yield the required result:
ByteArrayInputStream bais = new ByteArrayInputStream(byte[] yourData);
ObjectInputStream ois = new ObjectInputStream(bais);
ArrayList<String> al = new ArrayList<String>();
try {
Object obj = null;
while ((obj = ois.readObject()) != null) {
al.add((String) obj);
}
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (ois != null) {
ois.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
If your byte[] contains the ArrayList itself, you can do:
ByteArrayInputStream bais = new ByteArrayInputStream(byte[] yourData);
ObjectInputStream ois = new ObjectInputStream(bais);
try {
ArrayList<String> arrayList = ( ArrayList<String>) ois.readObject();
ois.close();
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (ois!= null) {
ois.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Something like this should suffice, forgive any compile typos I've just rattled it out here:
for(int i = 0; i < allbytes.length; i++)
{
String str = new String(allbytes[i]);
myarraylist.add(str);
}

yeah its possible, take each item from byte array and convert to string, then add to arraylist
String str = new String(byte[i]);
arraylist.add(str);

it depends very much on the semantics you expect from such a method. The easiest way would be, new String(bytes, "US-ASCII")—and then split it into the details you want.
There are obviously some problems:
How can we be sure it's "US-ASCII" and not "UTF8" or, say, "Cp1251"?
What is the string delimiter?
What if we want one of the strings to contain a delimiter?
And so on and so forth. But the easiest way is indeed to call String constructor—it'll be enough to get you started.

Related

Reading objects from assets

something is really messed up. I've got a ".ser" document in the assets folder, which stores an ArrayList of Objetcs. In an android application, I want to read this objects. There are a lot of posts related to this issue, however none of them could solve my problem. The strange part is, when I am using similar code in non - android context / "normal" java, it works properly. Here, the last line throws a NullPointerException - What is going wrong?
public void getData() {
ArrayList<MyClass> output= null;
InputStream is = null;
ObjectInputStream ois = null;
try{
is = this.getAssets().open("data.ser");
ois = new ObjectInputStream(is);
output = (ArrayList<MyClass>)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d("TAG", output.get(0).getId());
}
I would create a class and place the array within a single object:
public class ListObjects implements Serializable {
List<MyClass> listMyClass = new ArrayList<>();
public ListObjects(){
}
public List<MyClass> getListMyClass() {
return listMyClass;
}
public void setListMyClass(List<MyClass> listMyClass) {
this.listMyClass = listMyClass;
}
}
I had a similar problem. And it was because the name of the package in the java app was not called the same as the package name in android. And therefore I did not recognize them as equal objects. This is how I do it:
public static Object fromData(byte[] data) {
ObjectInputStream ois = null;
Object object = null;
try {
ois = new ObjectInputStream(
new ByteArrayInputStream(data));
object = ois.readObject();
} catch (Exception ex) {
Logger.getLogger(ModeloApp.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
ois.close();
} catch (Exception ex) {
Logger.getLogger(ModeloApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
return object;
}

Get data from getter method instead of passing in a Bundle

I need to pass some Bitmaps from one activity to another, and, since the size limit of the Bundle won't let me pass these images (even using a byte array*), I thought that I could use a getter method between these Activities.
-But, since I'm still not a master in Android (Java), I don't know if that would make any difference, and, if it does, what should I watch out for when using it.
the byte array did reduce the total size(at about 60%), but it still wasn't enough
scaling down is a way out, but just in case any other solution works
save your object in a file
private void saveDataToFile() {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = getContext().openFileOutput("fileName", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(yourObject); //which data u want to save
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Retrieve the object from another activity
private void getDataFromFile() {
FileInputStream fileInputStream = null;
try {
fileInputStream = getContext().openFileInput("fileName");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException |NullPointerException e) {
e.printStackTrace();
}
try {
yourObject = (ObjectClass) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Pass through Uri by writing getter method in POJO class
If you want to use getter setter, just create URI of your bitmap and pass to setter method in POJO class and then retrieve using getter method of POJO class.

output stream doesn't make a file

The code below is supposed to create and write to a file, but it doesn't create a file in my directory. Everything with the Scanner is working, it scans everything from jTextField perfectly.
OutputStream os;
try {
os = new FileOutputStream("kurinys.dat");
try (DataOutputStream dos = new DataOutputStream(os)) {
Scanner skanuoklisSaugojimui = new Scanner(jTextField1.getText());
while(skanuoklisSaugojimui.hasNextInt()){
int natosAukstis = skanuoklisSaugojimui.nextInt();
dos.writeInt(natosAukstis);
}
}
os.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
}
Can someone please help me find the problem?
Don't use a nested try, it doesnt have any sense and could case a lot of problems in terms of exception handling.
OutputStream os;
try {
os = new FileOutputStream("kurinys.dat");
}
catch (FileNotFoundException e) {
}
try (DataOutputStream dos = new DataOutputStream(os)) {
Scanner skanuoklisSaugojimui = new Scanner(jTextField1.getText());
while(skanuoklisSaugojimui.hasNextInt()){
int natosAukstis = skanuoklisSaugojimui.nextInt();
dos.writeInt(natosAukstis);
}
}
os.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
}

How to read multiple same objects from a file

I am trying to read objects from a file(same objects of a class), using Serializable, but whenit reads all objects it gives me error IOException, java.io.ObjectInputStream$BlockDataInputStream.peekByte.
I am reading objects and then saving to list. But as it reached lets say EOF it throws error.
Here is my method:
private static void updateBook(String name) {
// TODO Auto-generated method stub
FileInputStream fis = null;
ObjectInputStream in = null;
Object obj = new Object();
List<Object> libb = new ArrayList<Object>();
File file = new File(name + ".ser");
if (file.exists()) {
try {
fis = new FileInputStream(file);
in = new ObjectInputStream(fis);
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} finally {
in.close();
//fis.close();
}
for(int j = 0; j < libb.size(); ++j) {
Book li = new Book();
li = (Book) libb.get(j);
System.out.println(li.getBookName());
}
//
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("\nThe file does not Exist!");
}
}
Can anyone please tell me how to avoid this error from while(true).
Complete error:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
On your try statement you are missing the catch clause for the EOFException:
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} catch (EOFException eofe) {
// treat it as you like
} finally {
in.close();
//fis.close();
}
you should add:
catch (EOFException e){
// do stuffs
}
as EOFException is not being caught.

How to append an object to an existing file (generics)?

I'm having problems with appending a generic object within an existing file. This method is supposed to append the object to the existing file if the parameters are "true" and overwrites the entire file if "false". The "false" statement works perfectly fine, it overwrites the entire file but I can't seem to get the append one to work. It seems to do nothing at first glance but when I placed a simple System.out.println("test"); in the while (true) loop, it runs forever. How can I fix this?
public <T> void writeOneObject(T type, boolean append) throws NotSerializableException{
if (append == true){
//TODO
if (file.exists ()){
ObjectOutputStream ois = null;
try{
ois = new ObjectOutputStream (new FileOutputStream (file, true));
while (true){
ois.writeObject(type);
}
}catch (StreamCorruptedException e){
}catch (EOFException e){
}catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (ois != null) ois.close();
}catch (StreamCorruptedException e){
}catch (IOException e){
e.printStackTrace ();
}
}
}
}
else { //overwrites the entire file
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(type);
oos.flush();
oos.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (StreamCorruptedException e) {
System.out.println("error");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I also have this inside the class:
class NoHeaderObjectOutputStream extends ObjectOutputStream {
public NoHeaderObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
protected void writeStreamHeader() {}
}

Categories