java—当文件存在于同一目录中时,为什么会出现nosuchfileexception

nkkqxpd9  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(273)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

22小时前关门了。
改进这个问题
我的任务是编写一个包含两个线程的程序,每个线程观察一个文件,并在文件更改时将其打印到控制台。

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.concurrent.locks.ReentrantLock;
public class synch implements Runnable{

    ReentrantLock lock = new ReentrantLock();
    public static long firstThreadId;
    public static FileTime previous1;
    public static FileTime previous2;

    public void run(){
        if(firstThreadId == 0){
            firstThreadId = Thread.currentThread().getId();
        }

        while(true){
            if(firstThreadId == Thread.currentThread().getId()){
                adder(Thread.currentThread().getId());
            }else{
                adder(Thread.currentThread().getId());
            }
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

    public synchronized void adder(long threadID){
        if(firstThreadId == threadID){ // if first thread calls function
            Path filePath = Paths.get("C:\\Users\\ckola\\Documents\\Dokumente\\Studium\\2.semester\\Betriebssysteme\\Übungen\\Übung 6\\tes2.txt");
            try{
                FileTime modTime = Files.getLastModifiedTime(filePath);
                if(previous1.compareTo(modTime) < 0){
                    System.out.println("Dokument bearbeitet am: " + modTime);
                }
            }catch(Exception e){
                System.out.println(e + "1");
            }
        }else{ // if second thread calls function
            Path filePath = Paths.get("C:\\Users\\ckola\\Documents\\Dokumente\\Studium\\2.semester\\Betriebssysteme\\Übungen\\Übung 6\\test.txt");
            try{
                FileTime modTime = Files.getLastModifiedTime(filePath);
                if(previous1.compareTo(modTime) < 0){
                    System.out.println("Dokument bearbeitet am: " + modTime);
                }
            }catch(Exception e){
                System.out.println(e + "2");
            }
        }
    }

    public static void main(String[] args) throws Exception {
        test z = new test();
        Thread t1 = new Thread(z);
        Thread t2 = new Thread(z);

        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}

我现在的问题是,为什么会出现“nullpointereexception”或“java.nio.file.nosuchfileexception:c:\users\ckola\documents\dokumente\studium\2.terms\betriebsysteme”\ã?邦根\ã?bung 6\test.txt”,当所有文件都在同一目录下时?

brccelvz

brccelvz1#

您的npe来自这样一个事实:您的filetime变量(previous1和previous2)从未初始化。
文件路径可能是错误的,或者德语的umlauts可能会导致问题?
为什么要依赖线程ID来切换文件?只需编写一个以文件路径为参数的可运行类,并在代码中检查该文件即可。这将避免愚蠢的错误,例如在第二个文件的条件中检查previous1。

相关问题