Android Studio - FileWriter can't be assigned anything, remains null - java

I'm getting a null pointer exception in this method.
Taking a step by step debug and trying a couple different layouts and file writing methods I came to understand that my issue seems to be that I can't manage to find a way to properly assign value to a FileWriter object:
public void scriviEccezioneSuLog (String rigaDaScrivere){
try (FileWriter scrittoreFile = new FileWriter(fileLogUltimaEsecuzione, true)){ //TODO: null pointer exception
scrittoreFile.write("\n*ECCEZIONE: " + rigaDaScrivere);
} catch (IOException eccezioneScrituraFile) {
System.out.println("Eccezione nella scrittura del file di log.");
}
}
The fileLogUltimaEsecuzione File object is defined as:
private File fileLogUltimaEsecuzione = new File(Environment.getExternalStorageDirectory(), "/ultimaEsecuzione.log");
During debug the File object does indeed seem to have the intended value, so it is not null.
And yet after the try-with-resources:
FileWriter scrittoreFile = new FileWriter(fileLogUltimaEsecuzione, true)
scrittoreFile remains null.
Note:
I do not have this problem when trying the same code on a different java IDE (I tried running it on ApacheNetBeans and it is flawless).
EDIT:
Additional information:
The file ultimaEsecuzione.log is instantiated as a class variable and created in the constructor as follows:
try {
fileLogUltimaEsecuzione.createNewFile());
} catch (IOException ecccezioneIO) {
System.out.println("Eccezione IO nella creazione del file di log.");
}
However when I check .exists() on the file right after it should have been created I get "false".

Related

No NullPointerException on the logs

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.

Domino app - how to access the source document in java during custom file attachment routine

This is a non-xpages application.
I have inherited some code that I need to tweak....this code is used in a drag&drop file attachment subform. Normally, this will create a document in a separate dedicated .nsf that stores only attachments, and uses the main document's universalid as a reference to link the two....I need to change what the reference is to the value in a field already on the main document (where the subform is).
Java is challenging to me, but all I need to do is GET the value of the field from the main document (which has not necessarily been saved yet) and write that string value onto the attachment doc in that storage database, so I think I am just needing help with one line of code.
I will paste the relevant function here and hopefully someone can tell me how I get that value, or what else they need to see what is going on here.
You can see my commented-out attempt to write the field 'parentRef' in this code
...
private void storeUploadedFile( UploadedFile uploadedFile, Database dbTarget) {
File correctedFile = null;
RichTextItem rtFiles = null;
Document doc = null;
String ITEM_NAME_FILES = "file";
try {
if (uploadedFile==null) {
return;
}
doc = dbTarget.createDocument();
doc.replaceItemValue("form", "frmFileUpload");
doc.replaceItemValue("uploadedBy", dbTarget.getParent().getEffectiveUserName() );
Utils.setDate(doc, "uploadedAt", new Date() );
doc.replaceItemValue("parentUnid", parentUnid);
//doc.replaceItemValue("parentRef", ((Document) dbTarget.getParent()).getItemValue("attachmentDocKey"));
//get uploaded file and attach it to the document
fileName = uploadedFile.getClientFileName();
File tempFile = uploadedFile.getServerFile(); //the uploaded file with a cryptic name
fileSize = tempFile.length();
targetUnid = doc.getUniversalID();
correctedFile = new java.io.File( tempFile.getParentFile().getAbsolutePath() + java.io.File.separator + fileName );
//rename the file on the OS so we can embed it with the correct (original) name
boolean success = tempFile.renameTo(correctedFile);
if (success) {
//embed original file in target document
rtFiles = doc.createRichTextItem(ITEM_NAME_FILES);
rtFiles.embedObject(lotus.domino.EmbeddedObject.EMBED_ATTACHMENT, "", correctedFile.getAbsolutePath(), null);
success = doc.save();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
com.gadjj.Utils.recycle(rtFiles, doc);
try {
if (correctedFile != null) {
//rename the temporary file back to its original name so it's automatically
//removed from the os' file system.
correctedFile.renameTo(uploadedFile.getServerFile());
}
} catch(Exception ee) { ee.printStackTrace(); }
}
}
}
...
dbTarget.getParent does not do what you think it does. It returns a Session object that is the parent session containing all your objects. Casting it to (Document) won't give you your main document.
I don't see the declaration for it, but you appear to have a variable available called parentUNID. You can use it to get a handle on the main document.
You need to use the parentUNID value in a call to getDocumentByUNID() in order to retrieve the Document object representing your main document. But in order to do that, you need the Database object for the nsf file containing the main document, and if I understand you correctly, that is a different database than targetDb.
I'm going to have to assume that you already have that Database object in a variable called parentDb, or that you know the path to the NSF and can open it. In either case, your code would look like this (without error handling):
Document parentDoc = parentDb.getDocumentByUNID(parentUNID);
doc.replaceItemvalue("parentRef", parentDoc.getItemValue("attachmentDocKey"));

Change in file after creating FileOutputStream object even without writing anything into file

EDIT (for the sake of confusion): null has been written into the files "abc" and "efg".
After running the following code, the contents of file "abc" change which were initially null , and I get EOFException in every next execution :
ObjIStream = new ObjectInputStream(new FileInputStream("abc"));
M[][] objs = (M[][]) ObjIStream.readObject();
FS.objs = objs;
ObjIStream.close();
Here, FS.objs is a static member of class FS of type M[][] type.
On the other hand, this one has no effect on the file and I don't get any Exceptions after any number of executions:
ObjIStream = new ObjectInputStream(new FileInputStream("abc"));
M[][] objs = (M[][]) ObjIStream.readObject();
ObjIStream.close();
EDIT: I just found the trouble that exists in class FS in this form:
static{
try {
ObjOStream = new ObjectOutputStream(new FileOutputStream("abc"));
ObjOStream.close();
ObjOStream = new java.io.ObjectOutputStream(new java.io.FileOutputStream("efg"));
ObjOStream.close();
}
catch (IOException ex) { }
}
How is it troubling anyways?
The problem is new FileOutputStream("abc") itself, which means new FileOutputStream("abc", false). It cleans up all the data in file because you are not going to append anything. It calls FileOutputStream.open(String name, boolean append) which is a private native function. It erases everything in file in overwrite mode.

How do I update a properties value in java without deleting other variables

Content of data.txt file
pin=9876
balance=9001
investment=10000
interest=0.065
isLockedOut=false
My code currently:
import java.io.*;
import java.util.Properties;
public class SetData extends ATM {
public static void setIsLockedOut(boolean isLockedOut) { //Sets the isLockedOut variable
try {
Properties data = new Properties();
FileOutputStream output = new FileOutputStream("data.txt");
if (isLockedOut = true) {
data.setProperty("isLockedOut", "true");
data.store(output, null);
output.close(); //Closes the output stream
}
else {
data.setProperty("isLockedOut", "false");
data.store(output, null);
output.close();
}
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
I have also checked and referred to a similar question on StackOverflow as well (Updating property value in properties file without deleting other values).
The method 'setIsLockedOut' is called from another class.
When I call this method to set the 'isLockedOut' variable to true in the 'data.txt' file, all other variables are erased except the 'isLockedOut' variable. This is the output:
#Sun Nov 17 15:44:42 EST 2013
isLockedOut=true
So my question is, how can I update a property value without erasing the other values in the file?
All you are doing is overwriting the data.txt file with the content of data which is just the value of "isLockedOut". It seems that what you want to do is to overwrite data.txt with all of the properties that used to be in data.txt, plus an updated value for "isLockedOut". To do that, you need to open data.txt for reading and read its content into data, then modify data, then overwrite data.txt with the new data. Skipping the first step is what is causing your problem.
You need to use a FileInputStream and the load method. Use them much the same way you are using FileOutputStream and store already.

JXL library call

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.

Categories