0

I want to read a text file from src folder of class activitydata. In order to do that, I wrote following code

ActivityData c = new ActivityData();
         Class<? extends ActivityData> cls = c.getClass();
         URL url = cls.getResource("file.txt");
         System.out.println("Value = " + url);

Although I get the url in console, when I write following code I get exception:

Gson gson = new Gson(); 
JsonReader reader = new JsonReader(new FileReader(url.toString()));

Exception:

java.io.FileNotFoundException: file:\G:\Study%20Folder.......\file.txt (The filename, directory name, or volume label syntax is incorrect)
NNN
  • 87
  • 1
  • 2
  • 7

1 Answers1

0

In Java web applications, you can't assume you'll have access to your resources as Files. Use getResourceAsStream instead.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
  • Hi I managed to answer this question by following InputStream filestream = Thread.currentThread().getContextClassLoader().getResourceAsStream("MainDataScript.js"); Gson gson = new Gson(); JsonReader reader = new JsonReader(new InputStreamReader(filestream) ); – NNN Jan 29 '14 at 04:03
  • But I want to know, what if I want to write the same file ? – NNN Jan 29 '14 at 04:04
  • @ArkoMahmud You don't. You aren't guaranteed to be able to write inside a webapp. – chrylis -cautiouslyoptimistic- Jan 29 '14 at 04:24