This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a method that return an array of files in a given directory that is giving me a null pointer exception when executed. I can't figure out why.
private ArrayList<File> getFiles(String path) {
File f = new File(path);
ArrayList<File> files = new ArrayList<>(Arrays.asList(f.listFiles()));
return files;
}
thanks for your help
This NullPointerException is thrown when the path specified while initializing the file is incorrect (doesn't exist).
In such cases it is always advisable to add some null checks(protective code) in your method.
eg:
if( f != null) { //get the list of files }
may be casue by f.listFiles() return one null array.you can watch the variables in debug model
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I have a com.google.cloud.storage.Blob object. I have been able to download and upload just fine with this object in my java code, but I wanted to check if something exists before starting a process.In a nutshell here is the part of my code giving me issues.
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class Function implements BackgroundFunction<GcsEvent> {
public void accept(GcsEvent event, Context context) {
String bucketname = "my_bucket";
String blob_path = "path/to/my/object.jpg";
Storage storage = StorageOptions.newBuilder().setProjectId("my_project_id").build().getService();
Blob b = storage.get(BlobId.of(bucketname, blob_path));
// this is where the null pointer exception occurs
boolean exists = b.exists();
if (exists) {
//do something
}
}
}
Eclipse doesn't seem to catch it in the IDE. and the examples seem to follow this layout as well. Would anyone know what is going on?
I am running on a Linux environment machine. (it failed in cloud function as well).
I am using the Java 11 runtime.
I feel silly. I found out that storage.get(BlobId.of(bucketname, blob_path)); will return null if it can't find the object. instead of using b.exists(), one should check if it is null with if (b != null) { //do stuff }.
This question already has answers here:
How to negate a method reference predicate
(13 answers)
Closed 4 years ago.
Prior to Java 8, this method would be used to create a list of hidden files:
File[] hiddenFiles = new File("./directory/").listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isHidden();
}
});
In Java 8, this can be shortened to:
File[] hiddenFiles = new File("./directory/").listFiles(File::isHidden);
Returning non-hidden files in the original code was a trivial change: return file.!isHidden(); as a substitute for return file.isHidden();. I cannot recreate this functionality within a single line.
There is no isNotHidden function within the File class. Without creating one (or without deferring to the original, more verbose code), is there a way to recreate it using the new single-line style?
How about this,
File[] hiddenFiles = new File("c:/data").listFiles(f -> !f.isHidden());
Coming in java-11 Predicate.not, until then you can't via a method reference
Predicate.not(File::isHidden)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am adding objects to an ArrayList that is initialized as null inside a for each loop, but SonarLint is giving me a "NullPointerException" could be thrown when I try to add each object. Why is this error being pointed out?
public List<SatelliteData> getData()
{
SatelliteData satellite;
ArrayList<SatelliteData> satelliteList = null;
try(FileInputStream file = new FileInputStream(satelliteOutputFile))
{
TLEParser parsedFile = new TLEParser();
List<TLE> tleList = parsedFile.readFile(file);
for (TLE tle : tleList)
{
satellite = new SatelliteData(tle);
satellite.collectSatelliteData();
satelliteList.add(satellite); //A "NullPointerException" could be thrown; "satelliteList" is nullable here
}
}
catch (IOException ex)
{
LOGGER.error("IO Exception: " + ex);
notifyTheObservers("IO Exception: " + ex);
}
return satelliteList;
}
You shouldn't call member methods on variables that have been initialized to nothing/null.
In this case you have
ArrayList<SatelliteData> satelliteList = null;
This variable does not have any memory allocated to it.
At this point your computer knows : Okay there exists something
called satelliteData but it actually doesn't know where it is?
Calling add() method on it, is likely to throw a NullPointerException because this variable is a reference that is pointing to null/nothing.
To overcome this, You need to initialize the variable like this :
ArrayList<SatelliteData> satelliteList = new ArrayList<SatelliteData>();
At this point your computer created that satteliteData and knows
exactly where it exists hence it can happily operate upon it.
This will allocate some memory to this variable and now it has its own methods you can call.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried making a ticket using:
Ticket ticket = ForgeChunkManager.requestTicket(this, this.minecraftServer.entityWorld, ForgeChunkManager.Type.NORMAL);
The above code is in my main mod class. I get a NullPointerException when I try to run my mod.
in this case, either this.minecraftServer or this.minecraftServer.entityWorldis null.
try surrounding it with a if statement.
if (this.minecraftServer != null && this.minecraftServer.entityWorld != null){
Ticket ticket = ForgeChunkManager.requestTicket(this,
this.minecraftServer.entityWorld,
ForgeChunkManager.Type.NORMAL);
}
and for the purpose of debugging, I would suggest you separate it in two conditions:
if (this.minecraftServer == null) {
System.out.println("minecraftServer is null");
//or do anything can to warn you
} else if(this.minecraftServer.entityWorld == null) {
System.out.println("entityWorld is null");
//or do anything can to warn you
} else {
Ticket ticket = ForgeChunkManager.requestTicket(this,
this.minecraftServer.entityWorld,
ForgeChunkManager.Type.NORMAL);
}
Unless you can use a debugger to check the values.
But without the full code, it's impossible to know if there's any other error.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have to get the first element of an array., but it is possible that the element is empty; If the element is empty I put an empty field (I am trying to generate a pdf)
Here is my code now:
public void makePdf(Long id) throws IOException {
Candidacy ca = candidacyRepository.findOne(id);
cos.beginText();
cos.showText(
ca.getInterviews().stream().map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0)!=null?ca.getInterviews().stream().map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0):""));
cos.endText();
}
So I will wish not to prevent the generation of the pdf.
Thank you very much for your support!
UPDATE
Sorry for the lack of precision:
I also sort on the date.
public void makePdf(Long id) throws IOException {
Candidacy ca = candidacyRepository.findOne(id);
cos.beginText();
cos.showText(
ca.getInterviews().stream().sorted((a,b)-> a.getInterviewDate().compareTo(b.getInterviewDate())).sorted((a,f)->f.getInterviewDate().compareTo(a.getInterviewDate())).sorted((b,f)->b.getInterviewDate().compareTo(f.getInterviewDate())).map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0)!=null?ca.getInterviews().stream().sorted((a,b)-> a.getInterviewDate().compareTo(b.getInterviewDate())).sorted((a,f)->f.getInterviewDate().compareTo(a.getInterviewDate())).sorted((b,f)->b.getInterviewDate().compareTo(f.getInterviewDate())).map(Interview::getAgency).map(Agency::getAgencyName).collect( Collectors.toList()).get(0):""));
cos.endText();
}
I get a NullPointerException:/
Thank you for you help
This code doesn't make sense. You are executing the same Stream pipeline twice, and each time you generate an entire List when you only need the first element of that List.
You can use findFirst to get the first element of the Stream.
EDIT :
After testing my original answer, it turned out it doesn't work. findFirst() throws a NullPointerException if the first element is null.
You can avoid that by setting the default value before calling findFirst() :
ca.getInterviews().stream()
.map(Interview::getAgency)
.map(Agency::getAgencyName)
.map(s->s!=null?s:"") // this will replace null with ""
.firstFirst()
.get();