I am creating a HTML Webpage Generator as part of a college assignment. What I am trying to do is set the header by taking in the users text and saving it to string through the use of a get / set class. However when I try to output the text to file I get an error.
The code I am using to try and output the string is the following
public static void main(String[] args) throws IOException {
try {
File f = new File("C:\\Users\\David\\Desktop\\output.html");
if(!f.exists()) {
f.createNewFile();
}
FileWriter fw = new FileWriter(f);
fw.write(getHeader());
fw.close();
}catch(IOException io) {
Logger.getLogger(webPage.class.getName()).log(Level.SEVERE, null, io);
}
}
The error that Eclipse is giving me is
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at webPage.main(webPage.java:49)
Can anyone help me correct this please?
As JB Nizet's comment mentions, FileWriter.write() will throw an exception if the argument is null.
If you replace your write with fw.write("Hello World"), you will find no NPE.
So you need to figure out why getHeader() is returning null and fix that.
Related
I have a strange behaviour in my java code I would like to ask some advice.
In a multithreading application I wrote this code:
scratchDir.resolve(directoryTree).toFile().mkdirs();
For a bug the Object scratchDir is null, I was expecting a stack trace on the logs but there's nothing about the error.
I have checked the code and I never try to catch the NullPointerException.
Here is the complete method code:
#Override
public void write(JsonObject jsonObject) throws FileSystemException {
Path directoryTree = getRelativePath();
scratchDir.resolve(directoryTree).toFile().mkdirs();
String newFileName = getHashFileName(jsonObject);
Path filePath = scratchDir.resolve(directoryTree).resolve(newFileName);
logger.debug("Write new file Json {} to persistent storage dir {}", newFileName, scratchDir);
File outputFile = filePath.toFile();
if (outputFile.exists()) {
throw new FileAlreadyExistsException(filePath.toString());
}
try (FileWriter fileWriter = new FileWriter(outputFile)) {
fileWriter.write(jsonObject.toString());
fileWriter.flush();
} catch (Exception e) {
logger.error(e);
}
}
Why I don't have the exception in my logs?
Why are you doing this?
The proper way to do this is:
Files.createDirectories(scratchDir.resolve(directoryTree));
don't mix old and new API. The old mkdirs() api DEMANDS that you check the return value; if it is false, the operation failed, and you do not get the benefit of an exception to tell you why. This is the primary reason for why there is a new API in the first place.
Are you sure you aren't confused - and that is the actual problem? The line as you have it will happily do absolutely nothing whatsoever (no directories, and no logs or exceptions). The line above will throw if it can't make the directories, so start there.
Then, if that line IS being run and nothing is logged, then you've caught the NPE and discarded it, someplace you didn't paste.
I have a CSV file in Resources of my automation script and I need to amend one cell value to a parameter value I get by creating a folder in a site, I ran this code but then an error comes:
"(The process cannot access the file because it is being used by another process)".
Can anyone let me know how to write my parameter value to CSV file cell, please.
TIA
Method:
public static void writeCSV(String filePath, String separator) throws IOException {
try (OutputStream fileStream = new BufferedOutputStream(new FileOutputStream(filePath));
Writer outStreamWriter = new OutputStreamWriter(fileStream, StandardCharsets.UTF_8);
BufferedWriter buffWriter = new BufferedWriter(outStreamWriter)) {
buffWriter.append("https://mobile/sample_v4.zip");
buffWriter.append(separator);
buffWriter.append(createdTitle);
buffWriter.append(separator);
buffWriter.append("http://2-title-conversion/documentlibrary");
buffWriter.append(separator);
buffWriter.append("TRUE");
buffWriter.append(separator);
buffWriter.append("TRUE");
buffWriter.flush();
}
#Test segment,
loginPg.writeCSV("C:\\Users\\urathya\\Documents\\Automation\\03-11\\resources\\CS.csv",",");
You are not closing the output stream, please close it, it will close file and you can use the same file to append the data.
With ImageIO.write() API call, I get NullPointerException when I pass a non-existent path like "\\abc\abc.png". I pass the non-existent path purposely to test something but instead of getting FileNotFoundException, I get NPE. Why is that?
ImageIO.write() API is supposed to throw IOException but don't why I get NPE.
I use exception message string to show it in a message box to user but in this case NPE.getLocalizedMessage() returns empty string and hence the popup is empty with just an icon on it.
He is right, though. For example, this code:
public static void main(String[] args) throws IOException {
BufferedImage image = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
File out = new File("\\\\ABC\\abc.png");
ImageIO.write(image, "png", out);
}
gives
java.io.FileNotFoundException: \\ABC\abc.png (The network path was not found)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:233)
at javax.imageio.stream.FileImageOutputStream.<init>(FileImageOutputStream.java:69)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(FileImageOutputStreamSpi.java:55)
at javax.imageio.ImageIO.createImageOutputStream(ImageIO.java:419)
at javax.imageio.ImageIO.write(ImageIO.java:1530)
at javaapplication145.JavaApplication145.main(JavaApplication145.java:24)
Exception in thread "main" java.lang.NullPointerException
at javax.imageio.ImageIO.write(ImageIO.java:1538)
at javaapplication145.JavaApplication145.main(JavaApplication145.java:24)
The reason is that FileImageOutputStreamSpi.createOutputStreamInstance swallows the FileNotFoundException and then the NPE comes when ImageIO.write tries to close a stream that didn't open.
Why the exception is suppressed so brutally, I don't know. The code fragment is
try {
return new FileImageOutputStream((File)output);
} catch (Exception e) {
e.printStackTrace();
return null;
}
The only solution is to verify the path before attempting to use ImageIO.
I found out the reason for NPE for issue mentioned in this thread. Peter Hull is absolutely right in saying
public static void main(String[] args) throws IOException { BufferedImage image = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB); File out = new File("\\\\ABC\\abc.png"); ImageIO.write(image, "png", out); }
This is exactly my code looks like. Thanks Peter for highlighting.
The reason for this issue is that new FileImageOutputStream() throws a FileNotFoundException but some Sun programmer went and caught the exception, printed the stack trace, and returned null. Which is why it's no longer possible to catch the FileNotFoundException - it's already printed. Shortly afterwards, the returned null value causes a NullPointerException, which is what it being thrown from the method I called. When printed the Stack Trace of the exception, I could see FileNotFoundException along with NPE for the reason mentioned above.
-Nayan
i am a barely new to the java (was always on c# before) and need to create a swing application where i need to read a data from xls file. So i use jXL.
I have a class, which returns name of a first sheet from excel file, choosen in jFileChooser. Here is the code:
import java.io.File;
import jxl.Sheet;
import jxl.Workbook;
public class ExcelObject
{
private String filename = null;
private Workbook wb = null;
private Sheet sheet = null;
public ExcelObject(String f)
{
filename = f;
}
public String getSheetName()
{
String sheet_name = null;
try
{
wb = Workbook.getWorkbook(new File(filename));
sheet = wb.getSheet(0);
sheet_name = sheet.getName();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
wb.close();
}
return sheet_name;
}
}
in the program call looks like :
ExcelObject ex = new ExcelObject(filename);
String s = ex.getSheetName();
lblReport.setText(s);
So the issue is : when ran in the eclipse (3.4.2) i am getting a correct value, when jar is compiled, NO VALUE IS RETURNED! I mean lblReport is empty, with no exceptions and warnings.
Keep in mind : all other external jars work fine.
I tried a lot of things but none is working.
Also, if i do something like
ExcelObject ex = new ExcelObject(filename);
String s = ex.getSheetName();
// lblReportRun.setText(s);
lblReportRun.setText("Test");
lblAnyOtherLabel.setText("Test");
no text is displayed in the labels either, in compiled jar, and fine in eclipse.
This is probably because if some exception occurs when opening the workbook, you catch it, print the stack trace, and then close the workbook in the finally block. But since an exception occurred when calling Workbook.getWorkbook, the wb variable is still null, and you're trying to invoke close on it. So a NullPointerException happens while in the finally block.
Watch your console, you must have some exception popping up.
Also, note that fileName should be the only instance variable of your class, that Java variable normally don't contain underscores and use camelCase, and thet the fileName variable should be of type File, rather than String : you get a File from the file chooser, transform it into a string, and then transform it back to a File.
Another possibility, since it works in Eclipse and not when run externally, is that you forgot to put the jXL jar in the classpath, which causes some ClassNotFoundException when trying to use the ExcelObject class.
I tried to display the data from a doc file on console then i got this error
run:
The document is really a RTF file
Exception in thread "main" java.lang.NullPointerException
at DocReader.readDocFile(DocReader.java:36)
at DocReader.main(DocReader.java:47)
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)
can any one explain where i went wrong
the code is
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class DocReader {
public void readDocFile() {
File docFile = null;
WordExtractor docExtractor = null ;
WordExtractor exprExtractor = null ;
try {
docFile = new File("C:\\web.doc");
FileInputStream fis=new FileInputStream(docFile.getAbsolutePath());
HWPFDocument doc=new HWPFDocument(fis);
docExtractor = new WordExtractor(doc);
}
catch(Exception exep)
{
System.out.println(exep.getMessage());
}
String [] docArray = docExtractor.getParagraphText();
for(int i=0;i<docArray.length;i++)
{
if(docArray[i] != null)
System.out.println("Line "+ i +" : " + docArray[i]);
}
}
public static void main(String[] args) {
DocReader reader = new DocReader();
reader.readDocFile();
}
}
The document is really a RTF file
That's a typical message of an IllegalArgumentException from the HWPFDocument constructor. To the point it means that the supplied file is actually a (Wordpad) RTF file whose .rtf extension has incorrectly been renamed to .doc.
Supply a real MS Word .doc file instead and fix your code to not continue the flow when an exception has occurred. You need to throw it.
Just open the file in some Document program like Microsoft Office. Now save the same file with "Save As" option and choose .doc format.
That means, at line 36 of DocReader.java file, you are trying to invoke an API from an object but the object is not being created yet. So, the solution is to create an instance of the class first before making that API invocation.
UPDATE
My hunch tells me the NullPointerException happens at docExtractor.getParagraphText() because the docExtractor doesn't get initialized properly. Instead of swallowing the exception, print the stacktrace to figure out the actual problem, like this:-
try {
...
}
catch(Exception exep) {
exep.printStackTrace(); // do this
}