0

I have a question about package structure and reading and writing into files.

I am coding an eshop to learn java and now implented data exchange via sockets.

Since I am not using a data bank I am using .txt-files to write articles, new customers etc. into it. enter image description here

I now wanted to place the txt files into the server module in a package named "ressources". But then the compiler always said he couldn't find the files. I then named him the exact path to the "ressources" package and the reading worked.

public void openForReading(String dataSource) throws FileNotFoundException {
    //New code
    InputStream is = this.getClass().getResourceAsStream("/" + dataSource);
    InputStreamReader isr = new InputStreamReader(is);
    reader = new BufferedReader(isr);

    //old code, compiler said he couldn't find the file
    //reader = new BufferedReader(new FileReader(dataSource));
}

But when I registered a new customer and wrote him into the files he created a new file in the project directory instead of refreshing the file on the server in the package "ressources". I could fix that too with this code. but now he only refreshes the files in the directory "out".

public void openForWriting(String dataSource) throws IOException {
    //New code
    URL url = this.getClass().getResource("/" + dataSource);        
    File file = new File(url.getPath());
    writer = new PrintWriter(new BufferedWriter(new FileWriter(file)));

    //old code, not working - creates new file
    //writer = new PrintWriter(new BufferedWriter(new FileWriter(dataSource)));
}

Is there a way to refresh the files on the server and in the directory out?

5
  • Are you going to be writing data at runtime? That's important, as then the target is not a resource, but a data file and must be treated as a file in the file system, probably in an app directory off ${user.home}
    – g00se
    Commented Jul 21, 2023 at 10:37
  • Yes the data is written into the files at runtime.. So I can't have a resources package then? What do you mean by user.home?
    – Kaja S.
    Commented Jul 21, 2023 at 10:55
  • No you can't. You want mkdir "%USERPROFILE%\.EShop\data" from cmd.exe. Put your data files in there
    – g00se
    Commented Jul 21, 2023 at 11:36
  • I honestly have to say I am not quite sure If I got that. So I have to go into the cmd and enter "mkdir "%USERPROFILE%\.EShop\data" there. But where in intellij do I have to put the files?
    – Kaja S.
    Commented Jul 23, 2023 at 15:54
  • Yes. You don't put the files anywhere to do with IntelliJ. But you can drag them into the correct location which you'll see if you follow that command with explorer "%USERPROFILE%\.EShop\data"
    – g00se
    Commented Jul 23, 2023 at 15:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.