2

I am having a hard time understanding how reading file works in java. Now, I know how to write a code that reads a text file. Here is what I have.

BufferedReader file = new BufferedReader(new FileReader("/PATH_TO_THE_FILE"));

And this works very well.

Let's say "/PATH_TO_THE_FILE" is very specific to my computer. maybe it uses folder names that are different from other people, which also means this path is only valid on my computer, right?

In this case, what would happen if I (sender) zip this java and the text file together and send it to another person? My guess is that it won't work unless the receiver changes "/PATH_TO_THE_FILE" from the java file since it is written to work on the sender's computer.

I am not sure if my explanation is clear. Please let me know so I can make better edits!

Thanks

Isaac
  • 273
  • 3
  • 19
  • Do you run the program from your IDE or do you run it from a .jar file? Is the other computer supposed to run it from its IDE or as a jar file? – dinosaur Oct 30 '18 at 15:16
  • You have multiple options: 1) allow the program's user any way to input the filepath (e.g. command line [arguments](https://stackoverflow.com/questions/890966/what-is-string-args-parameter-in-main-method-java)). 2) use a [relative path](https://stackoverflow.com/questions/4210239/how-to-use-relative-path-instead-of-absolute-path) that finds your file next to the executable 3) load a path [property](https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html) from some form of program configuration. – SME_Dev Oct 30 '18 at 15:18
  • Does your program need to write to this file, or just read it? – VGR Oct 30 '18 at 15:35
  • Hi, Thank you all for replying. I am not sure what IDE is being used by the receiver to run this program. What I did is to pass the file name as an argument to the java process, as the accepted answer says. It now works well. Thank you all again! – Isaac Oct 30 '18 at 15:49

1 Answers1

1

Yes, that's what would happen.

You could pass the path to the file as an argument to the Java process. Then it is part of the arguments passed to

public static void main(String[] args)

This would make your code more portable.

  • Hey, Thanks for replying. I'm not sure what you mean by "pass the path to the file as an argument to the Java process." could you explain in an easier way? Sorry :( – Isaac Oct 30 '18 at 14:50
  • Take a look at https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html –  Oct 30 '18 at 15:23
  • Aha, I understand now. Solved it! Thank you so much :) – Isaac Oct 30 '18 at 15:47