0

I have a class Test and a folder with a textfile abc.txt in it. How can I write in this file? I have tried this, but it doesn't work (no Exception):

 public static void main(String[] args) throws IOException {       
    try { 
        PrintWriter pWriter = new PrintWriter(new BufferedWriter(new FileWriter("abc.txt"))); 
        pWriter.println("Hello World!"); 
    } catch (IOException ioe) { 
        ioe.printStackTrace(); 
    }   
}

When I write new FileWriter("/abc.txt") instead of new FileWriter("abc.txt") I get the following

Exception: java.io.FileNotFoundException: \abc.txt (Zugriff verweigert).

takendarkk
  • 2,949
  • 7
  • 22
  • 35
  • 1
    it can't find the file abc.txt because the name by itself doesn't exist in the file system. Try using the absolute path of the file as the name instead of just the name of the file. it will look something like "C:\user\doucments\abc.txt" – RAZ_Muh_Taz Apr 06 '18 at 21:29
  • But it also should run on other Computers. Is there another way? That's why i have put the textfile in the project package. –  Apr 06 '18 at 21:33
  • Sorry, i hadn't sayed that the textfile should included in the program. –  Apr 06 '18 at 21:43
  • 1
    No. Think about it. When you use MS word or whatever other text editor, does it store the file it creates inside the word.exe executable file? No, it doesn't. A writable file is data, that belongs **outside** of the program, where the user of the program decides to store its files. – JB Nizet Apr 06 '18 at 21:44
  • I mean i have a package and there i create a new folder. In that folder i want to store the textfile. And here is it also mentioned https://stackoverflow.com/questions/18091046/creating-runnable-jar-with-external-files-included, but i can't find a solution. –  Apr 06 '18 at 21:47
  • Forget about this idea. Packages are not folders. Packages are namespaces for your classes, to avoid name clashes and impose visibility barriers. At runtime, when the program is installed on a user computer, all the user has is a read-only jar file containing all the code. Basically the equivalent of en exe file. – JB Nizet Apr 06 '18 at 21:49

0 Answers0