Java says FileNotFoundException but file exists

前端 未结 10 1483
遇见更好的自我
遇见更好的自我 2020-11-22 10:19

I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am hav

10条回答
  •  长情又很酷
    2020-11-22 10:42

    Reading and writing from and to a file can be blocked by your OS depending on the file's permission attributes.

    If you are trying to read from the file, then I recommend using File's setReadable method to set it to true, or, this code for instance:

    String arbitrary_path = "C:/Users/Username/Blah.txt";
    byte[] data_of_file;
    File f = new File(arbitrary_path);
    f.setReadable(true);
    data_of_file = Files.readAllBytes(f);
    f.setReadable(false); // do this if you want to prevent un-knowledgeable 
                          //programmers from accessing your file.
    

    If you are trying to write to the file, then I recommend using File's setWritable method to set it to true, or, this code for instance:

    String arbitrary_path = "C:/Users/Username/Blah.txt";
    byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
    File f = new File(arbitrary_path);
    f.setWritable(true);
    Files.write(f, byte_array);
    f.setWritable(false); // do this if you want to prevent un-knowledgeable 
                          //programmers from changing your file (for security.)
    

提交回复
热议问题