Below is my code. I am converting images into bytearray values.
Here finalPathNames.size() == 4
So i want to save the byteArray values eachtime like byteArray1,byteArray2,byteArray3,byteArray4 which is inside for loop
Set<String> finalPathNames = sharedpre.getStringSet("prePathNames", null);
InputStream is = null;
for (String temp : finalPathNames) {
try {
is = new FileInputStream(temp);
try {
byteArray = streamToBytes(is);
} finally {
is.close();
}
} catch (Exception e) {
}
}
is there any optimized way to find result values
Send the bytes to the server, when you retrieve them or keep them in a list (in case you need them more than 1 time)
// as mentioned in the comments, user wants specifically 4 arrays
byte[][] byteArrays = byte[4][]; //
Set<String> finalPathNames = sharedpre.getStringSet("prePathNames", null);
InputStream is = null;
int index = 0;
for (String temp : finalPathNames) {
byteArrays[index] = new byte[0]; // in case of exception clear array. possibly set to null
try {
is = new FileInputStream(temp);
try {
byte[] byteArray = streamToBytes(is);
byteArrays[index] = byteArray;
} finally {
is.close();
}
} catch (Exception e) {
}
finally {
index++;
}
}
Then the resulting streams are available as:
byteArrays[0], byteArrays[1], byteArrays[2], byteArrays[3],
Related
I have the following piece of code:
public static byte[] readSomeFile(String filePath) {
byte[] buffer = new byte[FILE_SIZE];
FileInputStream fileIn = null;
BufferedInputStream buffIn = null;
DataInputStream inData = null;
int size = 0;
byte[] someArray= null;
try {
fileIn = new FileInputStream(filePath);
buffIn = new BufferedInputStream(fileIn);
inData = new DataInputStream(buffIn);
size = inData.read(buffer, 0, FILE_SIZE);
someArray= new byte[size];
System.arraycopy(buffer, 0, someArray, 0, size);
} catch (IOException e) {
//log(Log.ERROR,"IO ERROR: " + e.toString());
} finally {
try {
if (null != fileIn) {
fileIn.close();
}
if (null != buffIn) {
buffIn.close();
}
if (null != inData) {
inData.close();
}
} catch (Exception exFinally) {
// some stuff
someArray= null;
}
}
return someArray;
}
the problem is Sonar is still complaining about fileIn not being closed, although it's the first resource addressed in the finally block.
How does Sonar work in this case ? and how to resolve the Resources should be closed rule ?
If you have to use the Java 7 and above, I prefer you to use try with resources which was introduced in Java 7 new features.
Try-with-resources in Java 7 is a new exception handling mechanism that makes it easier to correctly close resources that are used within a try-catch block.
As to your code:
finally {
try {
if (null != fileIn) {
fileIn.close();
}
if (null != buffIn) {
buffIn.close();
}
if (null != inData) {
inData.close();
}
} catch (Exception exFinally) {
// some stuff
someArray= null;
}
}
Do you notice that ugly double try?
But, if you used the try with resources , close() is automatically called, if it throws an Exception or not, it will be supressed (as specified in the Java Language Specification 14.20.3) . Same happens for your case. I hope it helps.
So, your code will be looked like:
public static byte[] readSomeFile(String filePath) {
byte[] buffer = new byte[FILE_SIZE];
int size = 0;
byte[] someArray= null;
try (FileInputStream fileIn = new FileInputStream(filePath);
BufferedInputStream buffIn = new BufferedInputStream(fileIn);
DataInputStream inData = new DataInputStream(buffIn);) {
size = inData.read(buffer, 0, FILE_SIZE);
someArray= new byte[size];
System.arraycopy(buffer, 0, someArray, 0, size);
} catch (IOException e) {
//log(Log.ERROR,"IO ERROR: " + e.toString());
}
return someArray;
}
little bit of a pickle here. I am reading a JSON From a Zip file and I want to fill a table in Vaadin with the contents of the JSON.
Here's my Function to read the stuff and fill the table, this is Java.
private void getJsonContent() {
try {
FileInputStream fis = new FileInputStream(backupFile);
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
byte[] buffer = new byte[1024];
while((entry = zin.getNextEntry()) != null) {
if(entry.getName().equalsIgnoreCase("content.json")) {
int n;
while((n = zin.read(buffer, 0, 1024)) > -1){
String JSON = new String(buffer, Charset.forName("UTF-8"));
JSONObject obj = new JSONObject(JSON);
logger.info(JSON);
// Assign "global" Values to Variables
this.createdAt = obj.getString("created_at");
this.version = obj.getString("version");
// Fill table if applicable
for(int i = 0; i < obj.getJSONArray("content").length(); i++) {
JSONObject sub = obj.getJSONArray("content").getJSONObject(i);
logger.info(sub);
infoTable.addItem(new Object[] {
sub.get("imported_identities").toString(),
sub.get("project_versions").toString(),
sub.get("last_import").toString(),
sub.get("client").toString(),
sub.get("project").toString()
}, i +1);
}
}
}
}
zin.close();
fis.close();
} catch (FileNotFoundException e) {
// Can't happen here
} catch (IOException e) {
logger.info("Can't read File.");
} catch (JSONException jse) {
logger.info("JSON Content could not be read: " + jse.getMessage());
}
}
You will notice I have a function call logger.info(sub) - to make sure what I get is another valid JSON Object (the file I am reading contains nested things)
Output:
{"imported_identities":0,"project_versions":0,"last_import":null,"client":"Client1","project":"Project2"}
{"imported_identities":0,"project_versions":0,"last_import":null,"client":"Client2","project":"Project1"}
{"imported_identities":0,"project_versions":1,"last_import":"2016-09-14T09:28:24.520Z","client":"Client1","project":"Project1"}
I made sure all the values were correct (and the table is built with null as default) - here is the table properties:
infoTable.addContainerProperty(impIds, String.class, null);
infoTable.addContainerProperty(projVe, String.class, null);
infoTable.addContainerProperty(lstImp, String.class, null);
infoTable.addContainerProperty(client, String.class, null);
infoTable.addContainerProperty(projct, String.class, null);
infoTable.setColumnCollapsingAllowed(true);
infoTable.setColumnCollapsed(impIds, true);
infoTable.setColumnCollapsed(projVe, true);
infoTable.setColumnCollapsed(lstImp, true);
Finally, the table has "refreshRowCache" called on it. Anyone see the problem? There are no errors, no nothing, the table just doesn't add the item (the size of infoTable.getItemIds().size() is 0 right after the call.
EDIT:
I tried the following to verify.
infoTable.addItem(i + 1);
infoTable.getItem(i + 1).getItemProperty(impIds).setValue(sub.get("imported_identities").toString());
infoTable.getItem(i + 1).getItemProperty(projVe).setValue(sub.get("project_versions").toString());
This went and caused a NullPointerException, the stack trace however does not contain any of my classes as far as I can see.
The following is wrong:
The String constructor needs the read size (n).
while ((n = zin.read(buffer, 0, 1024)) > -1) {
String JSON = new String(buffer, 0, n, StandardCharsets.UTF_8);
Then you do JSONs of at most 1024 in the loop, instead on one JSON of it all
The bytes of a UTF-8 cannot be split at some point say at position 1024 and expect to have a valid complete multi-byte sequence at end and following block's begin.
Also there is readFully and closeEntry was missing.
In short:
private void getJsonContent() {
try (ZipInputStream zin = new ZipInputStream(new BufferedInputStream(
new FileInputStream(backupFile)))) {
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
if (entry.getName().equalsIgnoreCase("content.json")) {
long size = entry.getSize();
if (size > 100_000) {
throw new IllegalArgumentException("Data too large");
}
// We could use an InputStreamReader and read text piecewise.
// However JSON parsing also is easiest on an entire text.
byte[] buffer = new byte[(int)size];
int n = zin.readFully(buffer, 0, buffer.length);
String json = new String(buffer, StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(json);
logger.info(json);
// Assign "global" Values to Variables
this.createdAt = obj.getString("created_at");
this.version = obj.getString("version");
// Fill table if applicable
for (int i = 0; i < obj.getJSONArray("content").length(); i++) {
JSONObject sub = obj.getJSONArray("content").getJSONObject(i);
logger.info(sub);
infoTable.addItem(new Object[] {
sub.get("imported_identities").toString(),
sub.get("project_versions").toString(),
sub.get("last_import").toString(),
sub.get("client").toString(),
sub.get("project").toString()
}, i + 1);
}
} // if
zin.closeEntry(); // Do not forget preparing for the next entry
}
} catch (IOException e) {
logger.info("Can't read File.");
} catch (JSONException jse) {
logger.info("JSON Content could not be read: " + jse.getMessage());
}
}
The try-with-resources closes automatically even on exception or return.
I'm new to java and android programming and I want to convert string array to json. Here's the format:
String[][] filters = new String[2][5];
for(int i=0; i<5; i++){
filters[0][i] = "text";
}
for(int i=0; i<5; i++){
filters[1][i] = "text";
}
I tried
JSONArray mJSONArray = new JSONArray(Arrays.asList(filters));
session.editor.putString("filters",mJSONArray.toString());
session.editor.commit();
then I checked it by printing it out like this
System.out.println(session.pref.getString("filters", null);)
but the output is like this
["[Ljava.lang.String;#41b91028","[Ljava.lang.String;#41b910a8"]
The reason why I want to convert it to json is because I want to pass it to a SharedPreferences, which requires a string to be passed. Also, I would also like to know how to decode it. Thanks.
It depends on the library where you have the JSONArray class. But general approach should be that you create an empty JSONArray (for example let's call it parentJsonArray) and then, while looping through your 2 dimensional array elements you put other child JSONArray's into parentJsonArray. Should be something like this:
JsonArray parentJsonArray = new JsonArray();
// loop through your elements
for (int i=0; i<2; i++){
JsonArray childJsonArray = new JsonArray();
for (int j =0; j<5; j++){
childJsonArray.add(filters[i][j]);
}
parentJsonArray.add(childJsonArray);
}
After that, you can pass your parentJsonArray as a String into SharedPreferences and get it in the usual way how you get the simple String.
Converting String Array to jsonArray is not proper way to store to the SharedPreference because reverse is not possible then.
So I Would like to suggest convert string[][] array to Base64 String and store that string to shared preference and you can easily convert That string to String [][] back.
Use below functions to
private String convertTwoDimensionalStringArrayToString(String[][] s){
ByteArrayOutputStream bo = null;
ObjectOutputStream so = null;
Base64OutputStream b64 = null;
try {
bo = new ByteArrayOutputStream();
b64 = new Base64OutputStream(bo, Base64.DEFAULT);
so = new ObjectOutputStream(b64);
so.writeObject(s);
return bo.toString("UTF-8");
} catch (Exception e){
e.printStackTrace();
}finally {
try{
if (bo != null) { bo.close(); }
if (b64 != null) { b64.close(); }
if (so != null) { so.close(); }
}catch (Exception ee){
ee.printStackTrace();
}
}
return null;
}
private String[][] convertStringToTwoDimensionalStringArray(String s) {
ByteArrayInputStream bi = null;
ObjectInputStream si = null;
Base64InputStream b64 = null;
try {
byte b[] = s.getBytes("UTF-8");
bi = new ByteArrayInputStream(b);
b64 = new Base64InputStream(bi, Base64.DEFAULT);
si = new ObjectInputStream(b64);
return (String[][]) si.readObject();
}catch (Exception e){
e.printStackTrace();
} finally {
try{
if (bi != null) { bi.close(); }
if (b64 != null) { b64.close(); }
if (si != null) { si.close(); }
}catch (Exception ee){
ee.printStackTrace();
}
}
return null;
}
How to Use?
session.editor.putString("filters",convertTwoDimensionalStringArrayToString(filters));
session.editor.commit();
get back to String [][] ?
System.out.println(convertStringToTwoDimensionalStringArray(session.pref.getString("filters", null)));
You can use ObjectSerializer class (I've found it somewhere, but don't remember where). You can serialize your object to String and then save it into SharedPreferences as String value. When you need it back, just deserialize it back into object and use it.
There is example:
private void serializeTest() {
final String[][] filters = new String[2][5];
for(int i=0; i<5; i++){
filters[0][i] = "text";
}
for(int i=0; i<5; i++){
filters[1][i] = "text";
}
try {
final String serialized = ObjectSerializer.serialize(filters);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putString("KEY", serialized).apply();
} catch (IOException e) {
e.printStackTrace();
}
}
private void deserializeTest() {
final String serialized = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("KEY", "");
try {
final String[][] filters = (String[][]) ObjectSerializer.deserialize(serialized);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
And here's ObjectSerializer class source code:
http://pastebin.com/MgJbwYeP
I am making this J2ME application but I am having some problem when I am trying to save I thinks that it save properly but I am not sure....but when I retrieve it gives null
This is how I am storing them
PAR par = new PAR(oldMonPay, newMonPay, oldInterest);
par.setOldMPay(oldMonPay);
par.setNewMPay(newMonPay);
par.setOldInt(oldInterest);
And this is how I saving and retrieving
public static byte[] parseObjPAR(PAR p) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out;
try {
out = new DataOutputStream(baos);
out.writeUTF(p.getNewMPay());
out.writeUTF(p.getOldInt());
out.writeUTF(p.getOldMPay());
} catch (IOException e) {
}
return baos.toByteArray();
}
public static PAR parseByteArrPAR(byte[] b) {
PAR p = null;
ByteArrayInputStream bais;
DataInputStream in;
if (b != null) {
try {
bais = new ByteArrayInputStream(b);
in = new DataInputStream(bais);
p = new PAR(
in.readUTF(),
in.readUTF(),
in.readUTF());
} catch (IOException e) {
}
}
return p;
}
This is how I displaying the retrieved information, there is another problem this thing is not showing all the data but is only showing the 3 records. I think the first 3.
public void populatePAResult(PAR[] p) {
try {
for (int i = 0; i < p.length; i++) {
String oldMP = p[i].getOldMPay();
String newMP = p[i].getNewMPay();
String oldI = p[i].getOldInt();
result1.append("Day : " + oldMP, null);
result1.append("Time : " + oldI, null);
result1.append("Technology : " + newMP, null);
}
} catch (Exception e) {
}
}
In the parseObjPAR method that writes the data the order is:
out.writeUTF(p.getNewMPay());
out.writeUTF(p.getOldInt());
out.writeUTF(p.getOldMPay());
whereas when you read it back in and pass the order the constructor is expecting is different:
PAR par = new PAR(oldMonPay, newMonPay, oldInterest);
so even if it wasn't null the loaded data would be invalid.
Hi im decoding the base64 string data and saving into the database like url format with time stamp so i need to compress the decoded data and my compression like if the coming data is less than 100kb then no need to compress otherwise compress the data into 50% off.
try
{
String FileItemRefPath = propsFPCConfig.getProperty("fileCreationReferencePath");
String imageURLReferncePath = propsFPCConfig.getProperty("imageURLReferncePath");
File f = new File(FileItemRefPath+"/"+"productimages"+"/"+donorId);
String strException = "Actual File "+f.getName();
if(!f.exists())
{
if (!f.mkdirs())
{
System.out.println("direction creation failed");
return null;
}
}
else
{
boolean isdirCreationStatus = f.mkdirs();
}
String strDateTobeAppended = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
String fileName = strImageName+strDateTobeAppended;
savedFile = new File(f.getAbsolutePath()+"/"+fileName);
strException=strException+" savedFile "+savedFile.getName();
Base64 decoder = new Base64();
byte[] decodedBytes = decoder.decode(strImageBase64);
if( (decodedBytes != null) && (decodedBytes.length != 0) )
{
System.out.println("Decoded bytes length:"+decodedBytes.length);
fos = new FileOutputStream(savedFile);
System.out.println(new String(decodedBytes) + "\n") ;
int x=0;
{
fos.write(decodedBytes, 0, decodedBytes.length);
}
fos.flush();
}
if(fos != null)
{
fos.close();
System.out.println("file output stream"+savedFile.getName());
return savedFile.getName();
}
else
{
return null;
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if( fos!= null)
{
fos.close();
}
else
{
savedFile = null;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
return savedFile.getName();
}
Your main problem is probably not going to be compressing it in Java. For that you can simply use something like the Deflater class. On iOS however it might be a little more complicated, as I'm not sure what kind of zlib-like tools you have available in iOS.