0

I have a text file in my resource folder and I need to be able to read/remove/add text. I believe I have to use append so I tried this.

Files.write(Paths.get(Testing.class.getResource("/testresources/SearchList.txt").getPath())
, "the text".getBytes(), StandardOpenOption.APPEND);

This gives me back

Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 2: /C:/Users/Ben/workspace/Eve/bin/org/me/Testing/resources/SearchList.txt

If anyone could should me some clarity on this subject that would be great. Thankyou!

Bioflame
  • 7
  • 1
  • Looks like it's complaining about the `C:/` what type of OS are you on? Windows? – dolan Dec 24 '15 at 05:06
  • ya. I think you should be fine if that path resolved to `/Users/Ben/workspace/Eve/bin/org/me/Testing/resources/SearchList.txt` without the `C:/` – dolan Dec 24 '15 at 05:11
  • The program is going to be made into a jar file and run on multiple machines, will it still work then if its like that – Bioflame Dec 24 '15 at 05:14
  • Oh yup! Definitely want it to be generic. Just suggesting trying to find a method that generically returns something without the `C:/` – dolan Dec 24 '15 at 05:16

2 Answers2

0

This worked for me fine:

You should add the text file to a raw folder. If the raw folder does not exist in your resource directory, create one. And then in order to access it and write or edit it, use this:

OutputStream outputStream=getResources().openRawResource(R.raw.YourTextFile);

then in order to Read from the file, you should do this

InputStream inputStream=getResources().openRawResource(R.raw.YourTextFile);
john doe
  • 157
  • 1
  • 10
0

A leading slash is being automatically added to your path - /C:/Users/Ben/workspace/Eve/bin/org/me/Testing/resources/SearchList.txt

Lots of solutions have been suggested here in answers, Java NIO file path issue

Use any of those mentioned answers as your solution.

Also, for files intended to be in jar, You need to use Paths method public static Path get(URI uri) instead of public static Path get(String first,String... more) See How to get a path to a resource in a Java JAR file

Community
  • 1
  • 1
Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
  • I'm going to be making this a jar file and using it on multiple machines, I don' think having the direct route to the folder will work then. – Bioflame Dec 24 '15 at 05:19
  • I have edited my answer, you need to use uri if file is intended to reside in jar – Sabir Khan Dec 24 '15 at 05:52