11

I'm trying to make a .txt file available to my application via the class path. In my startup script--which is co-located in the same folder as the .txt file--I've set the following:

set CLASSPATH=%CLASSPATH%;%CD%\sample.txt java -classpath %CD%\sample.txt

In my application, I've tried the following:

  1. getClass().getResource("sample.txt")
  2. getClass().getResource("/sample.txt")
  3. getClass().getResource("classpath:sample.txt")

None of the above work. Any help would be appreciated.

Ignatius
  • 111
  • 1
  • 1
  • 3
  • 2
    Why are you trying to use the `CLASSPATH` for things that don't contain classes? – Daniel DiPaolo Jul 20 '11 at 15:41
  • 3
    @Daniel - It's fairly common to use the classpath for non-class resources (e.g. default property files, message bundles, templates). – Rob Hruska Jul 20 '11 at 15:45
  • Did you try `Thread.currentThread().getContextClassloader().getResource()`? The classloader used by `getClass` depends on the class you`re calling the method on. – home Jul 20 '11 at 15:47
  • Did you try using %CD%\ as a classpath instead of %CD%\sample.txt? If sample.txt is located in it, it should be found. – Shlublu Jul 20 '11 at 16:14
  • @Rob: All those things are possible, but none are the answer to Daniel's question. I'd like to hear why *Ignatius* is accessing resource that are not in a Jar file. Not theories, specifics. – Andrew Thompson Jul 20 '11 at 16:33
  • 1
    @Andrew - Sure, no problem asking for specifics. I just interpreted the comment broadly, i.e. "why would you ever do this?". I don't disagree that it would be nice to have the "why" for some context in this particular instance. – Rob Hruska Jul 20 '11 at 16:38
  • 1
    @Rob I think we are on the same wavelength. Thanks for clarifying. – Andrew Thompson Jul 20 '11 at 16:45

2 Answers2

4

You must pack you txt file inside jar or place it in directory included in classpath.

Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49
  • 7
    Wrong, of course you can add files to your classpath. For example (in *nix): java -cp "lib/*:etc" In lib you have a bunch of jar files and in etc you have .txt, .xml, .properties, etc. You then load them up with getResourceAsStream("myFile.txt") – Eldelshell Sep 13 '12 at 11:29
  • "Wrong, of course you can add files to your classpath." You've just repeated what this answers says - placing the files in a directory (`etc`), then adding that directory to the classpath (`java -cp etc`). – Adrian Baker Aug 29 '21 at 22:45
1

You should add to your classpath the directory containing the file, and not the file itself:

set CLASSPATH=%CLASSPATH%;%CD%
Eli Acherkan
  • 6,401
  • 2
  • 27
  • 34