for循环导致java.lang.NullPointerException

时间:2014-08-16 03:26:13

标签: for-loop nullpointerexception

我正在研究Java应用程序。当我尝试运行某个任务时,会导致java.lang.NullPointerException。这是错误:

java.lang.NullPointerException
at com.greenapple.program.core.TesterScript.buildStudentFileset(TesterScript.java:120)
at com.greenapple.program.core.TesterScript$1.run(TesterScript.java:83)

这是第117-124行:

public Set<StudentFiles> buildStudentFileset(String foo) {
    Set<StudentFiles> set = new HashSet<StudentFiles>();
    File[] studentFolders = new File(foo).listFiles(DirectoryFileFilter.instance().asFileFilter());
    for (int i = 0; i < studentFolders.length; i++) {
        set.add(new StudentFiles(studentFolders[i]));
    }
    return set;
}

这是第83行:

task = new TesterTask(buildStudentFileset("studentFolder"), new File(tester), testerName, addDep, name, millisPerTest, millisTotal);

我不知道为什么NullPointerException,有人可以帮帮我吗?

整个代码:

package com.greenapple.program.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;

@Immutable
public class TesterScript implements Testable {
    private final String name;
    private final String resultsFile;
    private final String studentFolder, tester, testerName;
    private final String addDep;
    private final int millisPerTest, millisTotal;
    private final UUID id;
    private Thread thread = null;
    public TesterScript(String scriptName, String folderOfStudentFolders, String testerPath, String testerBinaryName, String addDeps, int maxMillisPerTest, int maxMillisTotal, UUID ID, String writeResultsTo) {
        name = scriptName;
        resultsFile = writeResultsTo;
        id = ID;
        studentFolder = folderOfStudentFolders;
        tester = testerPath;
        testerName = testerBinaryName;
        addDep = addDeps;
        millisPerTest = maxMillisPerTest;
        millisTotal = maxMillisTotal;
    }
    public synchronized void test(Map<String, String> replace, final OneArgumentFunctor<Void, Progress> progressFunct, final TwoArgumentFunctor<Void, Testable, TesterResults> finishedFunct) {
        if (thread != null)
            return;
        final String resultsFile = doReplacement(this.resultsFile, replace);
        final String studentFolder = doReplacement(this.studentFolder, replace);
        final String tester = doReplacement(this.tester, replace);
        final String addDep = doReplacement(this.addDep, replace);
        final AtomicReference<TesterResults> res = new AtomicReference<TesterResults>();
        thread = new Thread() {
            Object fooLock = new Object();
            TesterTask task = null;
            ProgressTesterTaskRunner runner = null;
            public void run() {
                synchronized (fooLock) {
                    if (progressFunct != null)
                        progressFunct.invoke(new Progress("building task", 0, 1));
                    task = new TesterTask(buildStudentFileset("studentFolder"), new File(tester), testerName, addDep, name, millisPerTest, millisTotal);
                    runner = new ProgressTesterTaskRunner(task, progressFunct);
                }
                runner.compile();
                runner.run();
                res.set(runner.getResults());
            }
            public void interrupt() {
                synchronized (fooLock) {
                    if (runner != null)
                        runner.stop();
                }
            }
        };
        thread.start();
        while (thread.isAlive()) {
            try {
                thread.join();
            } catch (InterruptedException ex) {
                thread.interrupt();
                continue;
            }
        }
        if (res.get() != null)
            res.get().writeResultsToFile(new File(resultsFile), 3, true);
        ExecuteAfterThisThreadThread after = new ExecuteAfterThisThreadThread(Thread.currentThread(), new ZeroArgumentFunctor<Void>() {
            public Void invoke() {
                finishedFunct.invoke(TesterScript.this, res.get());
                return null;
            }
        });
        thread = null;
        after.start();
    }
    public Set<StudentFiles> buildStudentFileset(String foo) {
        Set<StudentFiles> set = new HashSet<StudentFiles>();
        File[] studentFolders = new File(foo).listFiles(DirectoryFileFilter.instance().asFileFilter());
        for (int i = 0; i < studentFolders.length; i++) {
            set.add(new StudentFiles(studentFolders[i]));
        }
        return set;
    }

    private Set<File> buildAddDepFileset(Set<String> foo) {

        return new HashSet<File>();
    }
    public UUID id() {
        return id;
    }
    public String name() {
        return name;
    }
    public void write(String filename) {
        write(new File(filename));
    }
    private void write(File file) {
        if (file.exists() && !file.isFile())
            throw new IllegalArgumentException("not a regular file: "+file);
        if (file.exists() && !FileUtils.isEmpty(file)) {
            new File(file.getPath()+".old").delete();
            file.renameTo(new File(file.getPath()+".old"));
            file.delete();
        }
        final String NEWLINE = "\n";
        try {
            FileWriter w = new FileWriter(file);
            w.write("JTTNG-Script/1.0"+NEWLINE);
            w.write("Script-ID: "+id().toString()+NEWLINE);
            w.write("Script-Name: "+name()+NEWLINE);
            w.write("Folder-of-Student-Folders: "+folderOfStudentFolders()+NEWLINE);
            w.write("Tester-Path: "+testerFile()+NEWLINE);
            w.write("Tester-Binary-Name: "+testerBinaryName()+NEWLINE);
            w.write("Additional-Dependencies-Length: "+"1"+NEWLINE);
            w.write("Additional-Dependencies: "+addDep+NEWLINE);
            w.write("Results-Path: "+resultsFile+NEWLINE);
            w.write("Per-Test-Timeout: "+millisPerTest+NEWLINE);
            w.write("Total-Timeout: "+millisTotal+NEWLINE);
            w.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
    public boolean hasSubtests() {
        return false;
    }
    public List<Testable> subtests() {
        return Collections.emptyList();
    }
    public synchronized void stop() {
        if (thread != null && thread.isAlive())
            thread.interrupt();
    }

    public String resultFile() {
        return resultsFile;
    }
    public String folderOfStudentFolders() {
        return studentFolder;
    }
    public String testerFile() {
        return tester;
    }
    public String testerBinaryName() {
        return testerName;
    }
    public String additionalDependencies() {
        return addDep;
    }
    public int millisPerTest() {
        return millisPerTest;
    }
    public int millisTotal() {
        return millisTotal;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof TesterScript))
            return false;
        return id().equals(((TesterScript)o).id());
    }
    @Override
    public int hashCode() {
        return id().hashCode();
    }
    @Override
    public String toString() {
        return name();
    }
    @Override
    public TesterScript clone() {
        return new TesterScript(name(), folderOfStudentFolders(), testerFile(), testerBinaryName(), additionalDependencies(), millisPerTest(), millisTotal(), id(), resultFile());
    }

    private String doReplacement(String foo, Map<String, String> replace) {
        for (Map.Entry<String, String> e : replace.entrySet())
            foo = foo.replace(e.getKey(), e.getValue());
        return foo;
    }

    public boolean canWriteResults(Map<String, String> replace) {
        FileOutputStream os = null;
        boolean retval = true;
        try {
            os = new FileOutputStream(doReplacement(resultFile(), replace));
        } catch (IOException e) {
            e.printStackTrace();
            retval = false;
        } finally {
            if (os != null)
                try {
                    os.close();
                } catch (IOException ex) {}
        }
        return retval;
    }
}

3 个答案:

答案 0 :(得分:2)

之后检查studentFolders变量是否为空
File[] studentFolders = new File(foo).listFiles(DirectoryFileFilter.instance().asFileFilter());
如果没有目录或指定为arg的文件,

listFiles()方法将返回null。

建议进行调试。

答案 1 :(得分:0)

空指针异常在第120行,可能是这一行:

File[] studentFolders = new File(foo).listFiles(DirectoryFileFilter.instance().asFileFilter());

如果String&#34; foo&#34;一片空白。或者这一行:

for (int i = 0; i < studentFolders.length; i++) {

如果String&#34; foo&#34;不是目录。

答案 2 :(得分:0)

固定它!有一个东西指向一个不存在的目录,所以它每次都崩溃了。谢谢大家!