Premature end of file between File and SAXReader - java

I am getting this exception "Error on line -1 of document : Premature end of file. Nested exception: Premature end of file." between lines of getting path of file and reading file using SAXReader
try {
LOG.info(" start parsing ");
SAXReader reader = new SAXReader();
File myfile = new File(fileName);
if (myfile.exists()) {
document = (Document) reader.read(fileName); // getting the exception here
}
else {
LOG.error(fileName + " does not exist");
new ExceptionErrorSupport(fileName,fileName+" does not exist","ECMException",true,CONTROLLER_CONSTANTS.ECM_ERROR_DIR);
}
} catch (DocumentException e) {
e.printStackTrace();
}
It seems that File() is not yet closing then SAXReader reads the file already but I cannot find a way to close File() see Why java.io.File doesn't have a close() method?.
Are there any ways to avoid this exception?
Thanks.

It seems that File() is not yet closing
No it doesn't. File() doesn't open anything, so there is nothing to close. And even if it did it wouldn't cause this exception. Your reasoning doesn't make sense.
If you got a premature end of file, it is because your input is malformed.

This can happen because the XML file you are reading is not properly formed.
That can mean a missing end tag, or even when an end of file character is not found.

Related

Why is this java code corrupting my pdf while checking access?

String pathSrc = "C:\\Users\\me\\Desktop\\somefile.pdf";
//should just check if file is opened by someone else
try
{
FileWriter fw = new FileWriter(pathSrc );
fw.close();
}
catch (IOException e)
{
System.out.println("File was already opened");
return;
}
This code should just check if pdf file is already opened. Instead after that code pdf file is corrupted. and can no longer be opened. Why is that?
Note that FileWriter starts empty everytime you instantiate a FileWriter with the Filename only, and then starts writing the data to the beginning of the file.
There's a second constructor that takes a boolean append flag that starts at the end of the file, appending data to the current file's contents.
This means that your code erases the whole pdf file and then close()s it, saving an empty PDF file, with zero bytes.
This simple change will fix your issue:
String pathSrc = "C:\\Users\\me\\Desktop\\somefile.pdf";
//should just check if file is opened by someone else
try {
FileWriter fw = new FileWriter(pathSrc, true);
fw.close();
}
catch (IOException e) {
System.out.println("File was already opened");
return;
}

Eclipse: Can't add a relative path to a .txt file to a Java application

I have a Java web application (running on Tomcat 9.0 on Linux) that retrieves a message (including a unique 4-letter location code), looks up the code in a CSV file and returns a human-readable location name. For example CLLK,Clear Lake.
The application was working well, when I'd loaded the file's absolute path /home/beau/eclipse-workspace/pagerfeed/brigades.csv.
But when I tried to change this to a relative path pagerfeed/brigades.csv, the file couldn't be found. Further investigation found that Eclipse was expecting to find the file at /home/beau/pagerfeed/brigades.csv, completely ignoring my eclipse-workspace folder.
Does anyone know what might be causing this?
Additionally, the file is currently just in the project's root directory, which I assume isn't best practice. Considering it will be deployed as a WAR file, is there somewhere better to put this file? (It can be accessible from the address bar.)
The code to load the file (yes it's messy - the commented lines are other methods I've tried that haven't worked properly):
// The code that actually gets the file (not working)
Brigade.importBrigadesFromFile("pagerfeed/brigades.csv");
// The code, when it WAS working
Brigade.importBrigadesFromFile("/home/beau/eclipse-workspace/pagerfeed/brigades.csv");
// And my background code to read the file
public Iterable<CSVRecord> read(String file) {
Iterable<CSVRecord> records = null;
try {
Reader reader = new FileReader(file);
// InputStream inputStream = getClass().getClassLoader().getResourceAsStream(file);
// InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
// BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
records = CSVFormat.DEFAULT.parse(reader);
System.out.println("Found the CSV file!");
} catch (FileNotFoundException fe) {
String absolutePath = new File("/data/testFile").getAbsolutePath();
System.out.println("File was not found.");
System.out.println("Try putting file here: " + absolutePath + ". ");
fe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Unable to parse the CSV file. Details: ");
ioe.printStackTrace();
} catch (NullPointerException ne) {
System.out.println("Could not read file at " + new File("filegoeshere").getAbsolutePath());
System.out.println("InputStream returned null. Details: ");
ne.printStackTrace();
}
return records;
}
Screenshot of my Eclipse path variables: https://imgur.com/a/Gnqrj

reading files with special characters from a zipfile

My code reads files from a zipfile , which works fine except for files with special characters. Problematic character is 'è' ( See my code fère_champenoise )
String works="(3/(3)_juno.jpa";
String sdoesntwork="ba/battle of fère_champenoise.jpa";
ZipFile file1 = null;
try {
file1 = new ZipFile(sZipFileOld);
} catch (IOException e) {
System.out.println("Could not open zip file " + sZipFileOld + ": " + e);
}
try {
file1.getInputStream(file1.getEntry(sdoesntwork));
} catch (IOException e) {
System.out.println(sdoesntwork + ": IO Error " + e);
e.printStackTrace();
}
it throws an error but doesn't go throught the exception handler:
Exception in thread "main" java.lang.NullPointerException
at java.util.zip.ZipFile.getInputStream(Unknown Source)
at ZipCompare.main(ZipCompare.java:56)
Any Solutions ?
When constructing the zipfile, explicitly specifying the encoding: file1 = new ZipFile(sZipFileOld, Charset.forName("IBM437"));
Zip files doesn't use the default UTF-8 encoding for special characters
I believe you need to specify an encoding, UTF-8 probably. Something like this:
final InputStream in = new InputStreamReader(file1.getInputStream(file1.getEntry(sdoesntwork)), "utf-8");
Make sure you remember to close this in a finally.
The problem is file1.getEntry(sdoesntwork) returns null because it does not find that entry.
If you are sure this name is correct, then try to use:
file1 = new ZipFile(sZipFileOld,StandardCharsets.UTF_8);
It doesn't go through your exception handler because is another type of exception, Null pointer exception is thrown because the entry is not found. You should check how or with which Charset the file has been define.
file1 = new ZipFile(sZipFileOld,StandardCharsets.UTF_8);
charset - The charset to be used to decode the ZIP entry name and comment (ignored if the language encoding bit of the ZIP entry's general purpose bit flag is set).
if the zip entry and its comment is ASCII, it is not necessary to use this way to construct the ZipFile.

How to write content to a file

try {
File file = new File("sample.txt");
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
fw.close();
} catch(IOException exp) {
exp.printStackTrace();
}
I am unable to append or write anything to the file.
But I could read the content from the file.
Is anything wrong with my code?
It sounds like you probably are writing to a file - but not the file you expect to. If no exceptions have been thrown (and swallowing an exception, just writing it to standard out, is rarely the right approach) then the file will exist somewhere.
It will be in whatever directory the code is running from - which may well not be the same as the directory containing the sample.txt file you're reading. I suggest you explore the file system, and also check the Run Configuration in Eclipse to see what the working directory for the app will be.
As an aside, you should be closing the writer in a finally block so that it gets closed even if there's an exception, like this:
File file = new File("sample.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file, true);
fw.append('d');
fw.write(100);
} catch(IOException) {
// Ideally do something to indicate the failure to the caller
// - do you need to catch this at all?
e.printStackTrace();
} finally {
// From Guava
Closeables.closeQuietly(fw);
}
Obviously you can do this without Guava but it'll make things a lot simpler - and not just here. If you're using Java 7 you can make it even simpler with a try-with-resources statement.
http://www.roseindia.net/java/example/java/io/java-write-to-file.shtml
You can Flush context if code is right and still you are facing problem. it "Flushes the stream"
This link can help!
Like was said before the file may be getting cleared out during the build/clean process. Try specificing an absolute path to the file and running it again. Everything you have written is correct sans the corrections already offered.
try {
File file = new File("C:\sample.txt"); // for Windows or possibly just "/sample.txt" for *nix
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
} catch(IOException e) {
e.printStackTrace();
} finally {
// Good practice to move close to a finally block
fw.close();
}
You may try using the below syntax :
String filename = "C:/sample.txt";
FileWriter fw = new FileWriter(filename,true);

Java, what to use instead of PrintStream to get exceptions?

I am creating a file on a network drive and then adding data to it. Time to time writing to that file fails. Is there a good way of checking if the file is accessible before every time i save data to it or maybe is tehre a way checking afther to see if the data was saved?
EDIT:
Right now i am using try-catch block with PrintStream in my code:
try
{
logfile = new File(new File(isic_log), "log_" + production);
//nasty workaround - we'll have a file the moment we assign an output stream to it
if (!logfile.exists())
{
prodrow = production;
}
out = new FileOutputStream(logfile.getPath(), logfile.exists());
p = new PrintStream(out);
if (prodrow != "")
{
p.println (prodrow);
}
p.println (chip_code + ":" + isic_number);
p.close();
}
catch (Exception e)
{
logger.info("Got exception while writing to isic production log: " + e.getMessage());
}
So might be the PrintStream the problem? (PrintWriter and PrintStream never throw IOExceptions)
I would use plain BufferedWriter and add the newlines myself as required.
Normal FileOutputStream operations should throw an IOException if there is an error.
AFAIK, The only exception is PrintWriter which does not throw an exception. Instead you need to call checkError() but it gives you no indication of what the error was or when it occurred.
I suggest you not use PrintWriter in this situation.
The only reasonable way to address this is to try to write to the file, and handle any resulting exception in an appropriate manner. It's pretty much impossible to know beforehand whether an I/O operation is going to succeed, due to the unreliable nature of networks.

Categories

Resources