http://pastebin.com/m5fa7685e
It seems to fail when getting f3.. Output is:
not ready
File is null
Exception in thread "main" java.lang.NullPointerException
at BuabFile.parseBUAB(BuabFile.java:93)
at AddressBook.createBrowseForm(AddressBook.java:232)
at AddressBook.(AddressBook.java:51)
at Main.main(Main.java:4)"
But not before then - no file not found errors or anything...
My guess would be that the parseBUAB() method receives a "null" argument. Which means that it could be that it is the AddressBook class is responsible for the error.
It looks like you forgot to assign a value to BuabFile.file static field. You may want to add this to the end of your readFile() method:
BuabFile.file = f3;
I am guessing your AddressBook.createBrowseForm method looks something like this:
String filename = ...;
BuabFile buab = new BuabFile(filename);
buab.readFile();
ArrayList<String> buabLines = buab.returnFile(); // Returns null because readFile() never assigned a value to BuabFile.file
ArrayList<Buab> buabList = buab.parseBUAB(buabLines);
From all I can see, you just call parseBUAB(..) with a null value. I can't see the call to that method so you have to check the rest of your code.
For your 'not ready' output, which is created because your BufferedReader f3 is 'not ready', the API says
True if the next read() is guaranteed not to block for input, false otherwise.
Maybe you just call it too fast and the file is not loaded yet. Play with Thread.sleep() before calling ready() on the stream. Maybe a some-milliseconds blocking is just normal for File I/O.
And third - if f3 is the BufferedReader you want to keep, you have to assign it to the member file in the readFile() method. But now that's all I found ;)
I'm confused further but have found an answer sort of - I'm using windows 7 and have tried it on a windows xp computer and the code compiles fine and reads in the file (other errors you lot have noted are to be changed anyway through development - this was just one stick in the way...).
I'm wondering if there is some Windows 7 error with eclipse and opening/reading files...
Related
I've written a small method that is meant to tell me if another instance of the application is already running. I am aware that there are many ways to find out if another instance is running, but I chose this one. I am creating an empty file and keeping it locked for the duration of the application instance. If another instance is running, the tryLock() method is supposed to return null:
private static boolean alreadyRunning() throws IOException {
FileChannel fc = FileChannel.open(MYLOCKFILE,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.DELETE_ON_CLOSE);
return fc.tryLock() == null;
}
(MYLOCKFILE is a Path for a file in my temp directory.)
When testing this on Windows 7 Professional 64-bit, I found that it works as expected for the first instance and the second attempted instance. However, after the second instance exits (leaving just the first instance running), when a third instance is run, the tryLock() call throws java.nio.file.AccessDeniedException instead of returning null. Can you explain this behaviour? If this is considered normal behaviour, how can I differentiate between an existing instance having the file locked, and a real 'access denied' situation such as an idiot setting the TEMP directory to read-only?
I made a test project and tested the code the only problem because of which java.nio.file.AccessDeniedException is thrown is StandardOpenOption.DELETE_ON_CLOSE option used in the code.
I removed the option and it works fine now
FileChannel fc = FileChannel.open(MYLOCKFILE, StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
Explanation that I can think because of which java.nio.file.AccessDeniedException is thrown is that as soon as your second instance terminates the option StandardOpenOption.DELETE_ON_CLOSE [More explaination] will attempt to delete the file on JVM exit and failing might have registered an event in kernel or OS to delete the file as and when possible. So if any other process tries to access, create or write the same file before deletion it throws java.nio.file.AccessDeniedException as a delete operation is already pending for that file.
EDIT
As per your new comment, you can add the following code in try finally block placed after checking alreadyRunning() code.
Snippet Example:
if(!alreadyRunning())
{
try
{
// YOUR CODE THAT RUNS
while(true)
{
//YOUR
Thread.sleep(35000);
}
}
finally
{
new File("f:\\test.lock").deleteOnExit();
}
}
I´m creating a table using iText.
But the output looks really bad, because of the hyphenation, which seems not to be done properly.
I allready read this question How to hyphenate text?
and this example http://itextpdf.com/sandbox/tables/HyphenationExample
I tried the example in eclipse after i added the itext_hyph_xml.jar to my class path. No error is thrown when i run the code, but the lines
Hyphenator h = new Hyphenator("de", "DE", 2, 2);
Hyphenation s = h.hyphenate("Leistungsscheinziffer");
System.out.println(s);
print null to the console instead of "Lei-stungs-schein-zif-fer" or something similar as i expected.
I tried playing with the parameters in
chunk.setHyphenation(new HyphenationAuto("de", "DE", 2,2));
but the output in the document never differes even slightly.
The code i´m trying to get to work looks kind of like this by the way:
for(String s: interest){
Chunk chunk = new Chunk(s,FONT[0]);
chunk.setHyphenation(new HyphenationAuto("de", "DE", 2,3));
table.addCell(new Phrase(chunk));
}
Ok I figured it out on my own now.
And because i couldn´t find the answer on the internet i thought i will share it here so anyone who might have the same error in the future wouldn´t need a week to figure it out.
It seems that in the class Hyphenator the defaultHyphLocation is set like this:
private static final String defaultHyphLocation = "com/itextpdf/text/pdf/hyphenation/hyph/";
But the structure of itext_hyph.jar looks like this:
com.lowagie.text.pdf.hyphenation.hyph
Obviously loading a hyph file from the jar will surely fail, since the path used by Hyphenator can not be found. I actually thought this would cause an error but it seems simply null is returned when the loading of the hyph file fails.
Calling Hyphenator.setHyphenDir("com/lowagie/text/pdf/hyphenation/hyph/"); however wouldn´t change a thing as one would think, since it changes the wrong string variable.
The only thing i could think of to solve this problem was to recreate the itext_hyph.jar according to the path given in Hyphenator and that acctually fixed it. Hyphenation is now working.
I am running into a peculiar issue (peculiar for me anyways) that seems to happen in a SwingWorker that I use for saving the result of another 'SwingWorker' thread as a tab-delimited file (just a spreadsheet of data).
Here is the worker, that initializes and declares an object which organizes the data and writes each table row to a file (using BufferedWriter):
// Some instance variables outside of the SwingWorker:
// model: holds a matrix of numerical data (double[][])
// view: the GUI class
class SaveWorker extends SwingWorker<Void, Void> {
/* The finished reordered matrix axes */
private String[] reorderedRows;
private String[] reorderedCols;
private String filePath; // the path of the file that will be generated
public SaveWorker(String[] reorderedRows, String[] reorderedCols) {
// variables have been checked for null outside of the worker
this.reorderedRows = reorderedRows;
this.reorderedCols = reorderedCols;
}
#Override
protected Void doInBackground() throws Exception {
if (!isCancelled()) {
LogBuffer.println("Initializing writer.");
final CDTGenerator cdtGen = new CDTGenerator(
model, view, reorderedRows, reorderedCols);
LogBuffer.println("Generating CDT.");
cdtGen.generateCDT();
LogBuffer.println("Setting file path.");
filePath = cdtGen.getFilePath(); // stops inside here, jumps to done()
LogBuffer.println("Path: " + filePath);
}
return null;
}
#Override
protected void done() {
if (!isCancelled()) {
view.setLoadText("Done!");
LogBuffer.println("Done saving. Opening file now.");
// need filePath here to load and then display generated file
visualizeData(filePath);
} else {
view.setReorderOngoing(false);
LogBuffer.println("Reordering has been cancelled.");
}
}
}
When I run the program from Eclipse, this all works perfectly fine. No issues whatsoever. Now I know there have been tons of question on here that are about Eclipse running fine while the runnable JAR fails. It's often due to not including dependencies or referring to them in the wrong way. But what's weird is that the JAR also works completely fine when it's being started from command line (Windows 8.1):
java -jar reorder.jar
Et voilà, everything as expected. The CDTGenerator will finish, write all the matrix rows to a file, and return the filePath. With the filePath I can subsequently open the new file and display the matrix.
In the case of double-clicking the JAR on my desktop, where I placed it when creating it from Eclipse, this is where the program will let me know that stuff happens. I get the error message I created for the case of filePath == null and using some logging I closed in on where the CDTGenerator object stops executing its method generateCDT() (Eclipse debugger also won't reproduce the error and do everything as planned).
What the log shows made me think it's an issue with concurrency, but I am actually leaning against that because Eclipse and command line both run the code fine. The log just tells me that the code suddenly stops executing during a loop which transforms double values from a matrix row (double[]) to Strings to be stored in a String[] for later writing with BufferedWriter.
If I use more logging in that loop, the loop will stop at a different iterator (???).
Furthermore, the code does work for small matrices (130x130) but not for larger ones (1500x3500) but I haven't tested where the limit is. This makes it seem almost time dependent, or memory.
I also used jVisualVM to look at potential memory issues, but even for the larger matrices I am on ~250MB which is nowhere near problematic regarding potential OutOfMemoryExceptions.
And finally, the last potential factor I can think of: Generating the JAR 'fails' due to some classpath issues (clean & rebuild have no effect...) but this has never been an issue before as I have run the code many many times using the 'broken' JAR and execute from Desktop.
I am a real newbie to programming, so please point in some direction if possible. I have tried to find logged exceptions, logged the values of variables, I am checking for null and IndexOutOfBound issues at the array where it stops executing... I am at a complete loss especially because this runs fine from command line.
It looks like the problem had to see with the java versions installed in OP's computer. They checked the file extensions and the programs associated to each one in order to see if it was the same java version as executed from Eclipse and the command line.
Once they cleaned older java versions the jar started to work by double-clicking it :)
Cause I do not have enough points (need 50 to directly answer your question), I need to ask this way:
If you double click a JAR you won't see a console which is often the problem because you can't see stack traces. They get just written to "nowhere". Maybe you get an NPE ore something else.
Try to attach an Exceptionhandler like this Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler) and let this handler write down a message to a file or such...
Just an idea.
How do I find out why java.io.File.mkdir() returns false.
I can create the directory manually.
UPDATE:
My code looks like this:
String directoryName = "C:/some/path/";
File directory= new File(directoryName );
if (!directory.exists() && !directory.mkdir()) {
throw new RuntimeException("Failed to create directory: " + directoryName);
}
You will need to use mkdirs() if the parent folder (some in your example) doesn't already exist.
The answer is simple, you're trying to create nested folders (a folder inside a folder). For nested folders use File.mkdirs(). That works, (tested).
I don't think you can, at least not from Java. Being that the OS makes that determination, Java is simply delegating to it and returning the result.
Have you tried ensuring that your File object is pointing where you think it is?
Update: if C:/some does not exist, it must first be created before you can attempt to create C:/some/path. Or use mkdirs() as was pointed out.
If you use something like process monitor for windows you can view the OS level attempt to create the directory.
That may give you the info you need.
You'll probably need to make use of the filters in process monitor because there's usually a lot of disk activity going on :)
Using cygwin?
mkdir may return false, but go on to create the folder anyway. The false seems only to indicate that the folder does not exist, yet.
You may have to try directory.exists() after the mkdir() call (or even mkdirs())
I am trying to update content in Google sites and am reading the stream in exception VersionConflictException.
When I check the stream it is all fine and is completely loaded in POST request but then I get following error.
org.apache.commons.fileupload.FileItemStream$ItemSkippedException
at org.apache.commons.fileupload.MultipartStream$ItemInputStream.read(MultipartStream.java:880)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at com.google.gdata.data.media.MediaSource$Output.writeTo(MediaSource.java:87)
at com.google.gdata.data.media.MediaBodyPart$MediaSourceDataHandler.writeTo(MediaBodyPart.java:74)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:452)
at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:157)
at com.google.gdata.wireformats.output.media.MediaMultipartGenerator.generate(MediaMultipartGenerator.java:58)
at com.google.gdata.wireformats.output.media.MediaMultipartGenerator.generate(MediaMultipartGenerator.java:37)
at com.google.gdata.client.Service.writeRequestData(Service.java:1831)
at com.google.gdata.client.media.MediaService.updateMedia(MediaService.java:497)
at com.google.gdata.data.media.MediaEntry.updateMedia(MediaEntry.java:159)
at morefile.UploadApp.updateAttachment(UploadApp.java:136)
FileItemStream.ItemSkippedException
This exception is thrown, if an
attempt is made to read data from the
InputStream, which has been returned
by FileItemStream.openStream(), after
Iterator.hasNext() has been invoked on
the iterator, which created the
FileItemStream.
I don't want to wake the zombies - this is just for future reference.
This is a basically a bad implementation of the apache-commons-fileupload. Calling hasNext() should NEVER render the result of the last next() call invalid. E.g. you can't do something like this
List collection;
while(hasNext(){
Object o = next();
collection.add(o);
}
Because if you access any item in the list it will result in an ItemSkippedException.
I got the same problem. I found it was caused by calling 'Streams.asString( stream)' twice. Reviewing the file upload source code, Streams.asString() will close the stream at the end of its operation, so if you call it again with the same stream, which is InputStream obtained from FileItemStream.openStream() by the way, you will get this exception. Fixed my program, and it works now as I intended!
I used to get this when I used to close the stream during iteration. Don't close the stream and it works fine.
Here is what was happening to me. I was getting this error because I had added
FileItemStream.openStream()
to the "Add Watch" in Intellij Idea, which is why it was throwing me this error.
Don't add this to watch while debugging.