MarcosCT7 MarcosCT7 - 1 year ago 57
Java Question

Java Error: NullPointerException

I'm totally new in this world. I want to make a simple file move program. It works fine with only 1 file and until I add the new code for multiple files move. But I wanted more and I added multiple file selection to

. To do the move of files I search around the web and found some users that asked for something similar to it. I tried to put it in my code but I've obtained an Error like this:

Exception in thread "main" java.lang.NullPointerException
at jfile.main(

Line 27 is: for (int i = 0; i < files.length; i++) {

This is the code, thanks you and sorry for my bad English.

import java.nio.file.Files;
import javax.swing.JFileChooser;
public class jfile {
public static void main (String[] args) throws IOException{

System.out.println("Creado por: MarcosCT7");

if (new File(System.getProperty("user.home"), "\\AppData\\Roaming\\.minecraft\\mods").exists());{
System.out.println("Seleccione el mod a instalar:");
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(chooser);

if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("Se está instalando " + chooser.getSelectedFile().getName());
File fuente = new File(chooser.getSelectedFile().getAbsolutePath());
File destino = new File(System.getProperty("user.home"), "\\AppData\\Roaming\\.minecraft\\mods");

File[] files = fuente.listFiles(); //thats new added
for (int i = 0; i < files.length; i++) {
File destFile = new File(destino.getAbsolutePath()+File.separator+files[i].getName().replace(",", "")
.replace("[", "")
.replace("]", "")
.replace(" ", "")); //until here its new added
FileUtils.moveFileToDirectory(files[i], destFile, true); //changed to multiple move, before it was: FileUtils.moveFileToDirectory(fuente, destino, true);


else {
if(returnVal == JFileChooser.CANCEL_OPTION) {
System.out.println("No se ha seleccionado ningun mod. Adios.");

Answer Source

NullPointerException means that the variable doesn't hold any reference to a object. What I mean by reference is, For ex:

String path="";
File f=new File(path);
if(f.exists()) {
   // do something

f is a variable of type File which holds a reference to a object File defined by path and now you can use variable f just like any other variable call methods on that variable etc. Another example

File f;

if(f.exists()) {
   // do something

Now you will get NullPointerException in line if(f.exists()) because f doesn't hold any reference.

In JAVA new keyword is used to assign new reference. JVM will take care of all the low level details. It is similar to pointers in c and c++. In JAVA you don't have to explicitly delete the objects. JVM garbage collector will take care of these things. Java is object oriented language

Do read and understand OOP comcepts