Main problem is that I get null result from my zipEntry. What I am doing is getting BLOB.zip from database, directing it to input stream, from there to zipArchiveInputStream and to ZipEntry which returns null every time. I decided to use ZipArchiveInputStream after using ZipInputStream with same null results.
public byte[] getXMLStream() {
try {
return this.jdbcTemplate.queryForObject("SELECT SAVEDATA FROM JDBEVPP1.TEVP005 WHERE GFNR = 357420", byte[].class); }
catch(DataAccessException ex) {
ex.printStackTrace();
return null;}}
#Override
public void getXMLdata() {
byte[] str = getXMLStream();
InputStream myInputStream = new ByteArrayInputStream(str);
ZipArchiveInputStream fis = new ZipArchiveInputStream(myInputStream);
ZipEntry entry = null;
try {
while ( (entry = fis.getNextZipEntry()) != null ) {
System.out.println(entry.getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
I just need to get this xml and print it in console for testing. Any idea what is wrong here or how to make it work?
EDIT: Inside BLOB is XML format which I need to present on console.
I solve this problem by using GZIPInputStream. It seems it is generic xml at the end..
try {
GZIPInputStream gzip = new GZIPInputStream(bys);
Reader decoder = new InputStreamReader(gzip, "UTF-8");
BufferedReader buffered = new BufferedReader(decoder);
System.out.println(buffered.readLine());
String data = buffered.readLine();
InputSource xml = new InputSource(new StringReader(data));
System.out.println(xml);
} catch (IOException e) {
e.printStackTrace();
}
Related
I know I'm not doing something correctly. I know the file needs to be Serializable to read a text file.
I've got implements Serializable on the main class. But my readText and my writeText aren't converting.
Nothing is coming in when I read and when I write out the file is not text.
public static ArrayList<String> readText() {
ArrayList<String> read = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Reading serialized file",
FileDialog.LOAD);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File inFile = new File(dirPath + foName);
BufferedReader in = null;
ObjectInputStream OIS = null;
try {
in = new BufferedReader(new FileReader(inFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = null;
try {
line = in.readLine();
} catch (IOException e1) {
e1.printStackTrace();
while (line != null) {
try {
FileInputStream IS = new FileInputStream(inFile);
OIS = new ObjectInputStream(IS);
inFile = (File) OIS.readObject();
} catch (IOException io) {
io.printStackTrace();
System.out.println("An IO Exception occurred");
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace(); // great for debugging!
System.out.println("An IO Exception occurred");
} finally
{
try {
OIS.close();
} catch (Exception e) {
}
}
}
}
return read;
}
public static void writeText(ArrayList<String> file) {
ArrayList<String> write = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Saving customer file",
FileDialog.SAVE);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File outFile = new File(dirPath + foName);
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
for (int i = 0; i < write.size(); i++) {
String w = write.get(i);
out.println(file.toString());
}
}
catch (IOException io) {
System.out.println("An IO Exception occurred");
io.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
Nothing is coming in
You're never calling read.add(line) and you're attempting to read the file within an infinite loop inside of the catch block, which is only entered if you are not able to read the file.
Just use one try block, meaning try to open and read the file at once, otherwise, there's no reason to continue trying to read the file if it's not able to be opened
List<String> read = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(inFile)) {
String line = null;
while ((line = in.readLine()) != null) {
read.add(line); // need this
}
} catch (Exception e) {
e.printStackTrace();
}
return read;
Now, whatever you're doing with this serialized object stuff, that's completely separate, and it isn't the file or your main class that needs set to Serializable, it's whatever object you would have used a writeObject method on. However, you're reading and writing String objects, which are already Serializable.
when I write out the file is not text
Not sure what you mean by not text, but if you followed the above code, you'll get exactly what was in the initial file... Anyway, you do not need a write list variable.
You must use the individual lines of ArrayList<String> file parameter instead, but not file.toString()
for (String line:file) {
out.println(line);
}
out.close(); // always close your files and writers
we have a piece of code which generates a zip file on our system. Everything is ok, but sometimes this zip file while opened by FilZip or WinZip is considered to be corrupted.
So here is my question: how can we check programatically if a generated zip file is corrupted?
Here is the code we are using to generate our zip files:
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tmpFile));
byte[] buffer = new byte[16384];
int contador = -1;
for (DigitalFile digitalFile : document.getDigitalFiles().getContent()) {
ZipEntry entry = new ZipEntry(digitalFile.getName());
FileInputStream fis = new FileInputStream(digitalFile.getFile());
try {
zos.putNextEntry(entry);
while ((counter = fis.read(buffer)) != -1) {
zos.write(buffer, 0, counter);
}
fis.close();
zos.closeEntry();
} catch (IOException ex) {
throw new OurException("It was not possible to read this file " + arquivo.getId());
}
}
try {
zos.close();
} catch (IOException ex) {
throw new OurException("We couldn't close this stream", ex);
}
Is there anything we are doing wrong here?
EDIT:
Actually, the code above is absolutely ok. My problem was that I was redirecting the WRONG stream for my users. So, instead of opening a zip file they where opening something completely different. Mea culpa :(
BUT the main question remains: how programatically I can verify if a given zip file is not corrupted?
You can use the ZipFile class to check your file :
static boolean isValid(final File file) {
ZipFile zipfile = null;
try {
zipfile = new ZipFile(file);
return true;
} catch (IOException e) {
return false;
} finally {
try {
if (zipfile != null) {
zipfile.close();
zipfile = null;
}
} catch (IOException e) {
}
}
}
I know its been a while that this has been posted, I have used the code that all of you provided and came up with this. This is working great for the actual question. Checking if the zip file is corrupted or not
private boolean isValid(File file) {
ZipFile zipfile = null;
ZipInputStream zis = null;
try {
zipfile = new ZipFile(file);
zis = new ZipInputStream(new FileInputStream(file));
ZipEntry ze = zis.getNextEntry();
if(ze == null) {
return false;
}
while(ze != null) {
// if it throws an exception fetching any of the following then we know the file is corrupted.
zipfile.getInputStream(ze);
ze.getCrc();
ze.getCompressedSize();
ze.getName();
ze = zis.getNextEntry();
}
return true;
} catch (ZipException e) {
return false;
} catch (IOException e) {
return false;
} finally {
try {
if (zipfile != null) {
zipfile.close();
zipfile = null;
}
} catch (IOException e) {
return false;
} try {
if (zis != null) {
zis.close();
zis = null;
}
} catch (IOException e) {
return false;
}
}
}
I think you'll see correspondent exception stack trace during zip-file generation. So, you probably wan't to enhance your exception handling.
in my implementation it looks like that. maybe it helps you:
//[...]
try {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(file.getName()));
try {
final byte[] buf = new byte[BUFFER_SIZE];
while (true) {
final int len = bis.read(buf);
if (len == -1) {
break;
}
zos.write(buf, 0, len);
}
zos.flush();
zos.closeEntry();
} finally {
try {
bis.close();
} catch (IOException e) {
LOG.debug("Buffered Stream closing failed");
} finally {
fis.close();
}
}
} catch (IOException e) {
throw new Exception(e);
}
//[...]
zos.close
Perhaps swap the following two lines?;
fis.close();
zos.closeEntry();
I can imagine that the closeEntry() will still read some data from the stream.
Your code is basically OK, try to find out which file is responsible for the corrupted zip file. Check whether digitalFile.getFile() always returns a valid and accessible argument to FileInputStream. Just add a bit logging to your code and you will find out what's wrong.
new ZipFile(file)
compress again the file, so duplicate efforts and that is not what you are looking for. Despite of the fact that only check one file and the question compress n-files.
Take a look to this: http://www.kodejava.org/examples/336.html
Create a checksum for your zip:
CheckedOutputStream checksum = new CheckedOutputStream(fos, new CRC32());
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(checksum));
...
And when you finish the compression show it
System.out.println("Checksum : " + checksum.getChecksum().getValue());
You must do the same reading the zip with java or others tools checking if checksums match.
see https://stackoverflow.com/a/10689488/848072 for more information
ZipOutputStream does not close the underlying stream.
What you need to do is:
FileOutputStream fos = new FileOutputStream(...);
ZipOutputStream zos = new ZipOutputStream(fos);
Then in your closing block:
zos.close();
fos.flush(); // Can't remember whether this is necessary off the top of my head!
fos.close();
I have requirement, where i need to get the xml from the server to parse if it is present and if not take the file from assets folder.
What ever the xml i'm getting using inputstream im passing it as the parameter for StringReader for further processing. I'm using XmlPullParser for parsing.
But i'm not able to pass the inputsource paramter to stringreader for further parsing. I don't to use document reader. Please find the code as below.
private void readSynconfiguration( )
{
XmlParser xmlparser = new XmlParser();
try {
String strFromMbo = getDataFromMBO();
if(strFromMbo != null && !strFromMbo.isEmpty()) { // first
InputSource is = new InputSource(new StringReader(strFromMbo));
// result = getStringFromInputStream(is);
}
else {
context = RetailExecutionApplication.getApp().getApplicationContext();
InputStream stream = context.getAssets().open("syncSettings.xml");
result = getStringFromInputStream(stream);
}
} catch (IOException e) {
syncSetting = false;
e.printStackTrace();
}
StringReader labelReader = new StringReader(result);
try {
if(syncSetting) {
labelSharedInstance.clear();
labelSyncDetails = xmlparser.LabelsParse(labelReader);
labelSharedInstance = labelSyncDetails;
}
} catch (XmlPullParserException e) {
syncSetting = false;
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me in this regard.
You can not pass inputsorce object directly to StringReader. First of all you convert inputsorce to reader as follows :
Reader reader = yourInputSource.getCharacterStream();
String result = reader.toString();
StringReader labelReader = new StringReader(result);
I think you are confusing things. The XmlPullParser.setInput() method takes Reader, so that's what you need to provide.
In case 1 (from database), you have a String in strFromMbo, so just wrap with a StringReader.
In case 2 (from file), you have two choices:
Load entire file into memory as a String. This is what you're doing.
Use a FileReader. Uses less memory.
In both cases, remember to close your resources.
I don't understand what "inputsource" has to do with anything.
String xml = getDataFromMBO();
if (xml == null || xml.isEmpty()) {
context = RetailExecutionApplication.getApp().getApplicationContext();
try (InputStream stream = context.getAssets().open("syncSettings.xml")) {
xml = getStringFromInputStream(stream);
} catch (IOException e) {
syncSetting = false;
e.printStackTrace();
}
}
if (syncSetting) {
try {
labelSharedInstance.clear();
labelSyncDetails = new XmlParser().LabelsParse(new StringReader(xml));
labelSharedInstance = labelSyncDetails;
} catch (XmlPullParserException e) {
syncSetting = false;
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I need to save an arraylist of hashmaps to an external file. I can use any format expect for a text file, because the program is set to ignore text files (specially, anything with a .txt extension). The hashmaps are pretty straightforward, just words with counts of those words. What is the ideal file format to store this in?
You could use java.util.Properties.
Properties properties = new Properties();
properties.putAll(yourMap); // You could also just use Properties in first place.
try (OutputStream output = new FileOutputStream("/foo.properties")) {
properties.store(output, null);
}
You can read it later by
Properties properties = new Properties();
try (InputStream input = new FileInputStream("/foo.properties")) {
properties.load(input);
}
// ... (Properties implements Map, you could just treat it like a Map)
See also:
Java Tutorials - Essential Classes - Properties
You could use serialization:
ObjectOutputStream stream = null;
try
{
File f = new File(filename);
stream = new ObjectOutputStream(new FileOutputStream(f));
stream.writeObject(your_arraylist);
}
catch (IOException e)
{
// Handle error
}
finally
{
if (stream != null)
{
try
{
stream.close();
}
catch (Exception e) {}
}
}
And read it in using:
ObjectInputStream stream = null;
try
{
stream = new ObjectInputStream(new FileInputStream(f));
your_arrayList = (your_arrayList type here)stream.readObject();
}
catch (Throwable t)
{
// Handle error
}
finally
{
if (stream != null)
{
try
{
stream.close();
}
catch (Exception e) {}
}
}
I have a resource file in my /res/raw/ folder (/res/raw/textfile.txt) which I am trying to read from my android app for processing.
public static void main(String[] args) {
File file = new File("res/raw/textfile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Do something with file
Log.d("GAME", dis.readLine());
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried different path syntax but always get a java.io.FileNotFoundException error. How can I access /res/raw/textfile.txt for processing? Is File file = new File("res/raw/textfile.txt"); the wrong method in Android?
***** Answer: *****
// Call the LoadText method and pass it the resourceId
LoadText(R.raw.textfile);
public void LoadText(int resourceId) {
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Note this will return nothing, but will print the contents line by line as a DEBUG string in the log.
If you have a file in res/raw/textfile.txt from your Activity/Widget call:
getResources().openRawResource(...) returns an InputStream
The dots should actually be an integer found in R.raw... corresponding to your filename, possibly R.raw.textfile (it's usually the name of the file without extension)
new BufferedInputStream(getResources().openRawResource(...)); then read the content of the file as a stream