Get file to be read from another package - java

I need to catch a file that is package called files
I try use getResourceAsStream or
File file = getClass().getResourceAsStream("files/big.txt"));
However, is not working. This saying to convert for URL. If in this case I to use URL, I could do a downcasting, but is not working.
What I can do to solve that issue?

add one more slash "/" - If you are accessing from another package
As Commented Information, To Read the File use openStream() of URL
URL url = getClass().getResource("/files/big.txt");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String nameList;
while ((nameList = in.readLine()) != null) {
System.out.println(nameList);
}
} catch (Exception e) {
e.printStackTrace();
}

If you want the file object you can call
fileUrl.getFile()
to get the file object

Related

How do I read from a .txt file inside of a resource directory folder?

Here's what I need to happen: I've got a text file with some values in them that I need to read (Let's say it is example.txt). I need to read that file like i would using ex. FileInputStream or BufferedReader). How would I go about doing it?
PS - This is what I tried doing, but it didn't help. I would always get an error saying the file has to be .xml
try {
BufferedReader bufferReader = new BufferedReader(new FileReader(file);
try {
String line = bufferReader.readLine();
while(line != null) {
//do something
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Java convert inputStream to URL

How can I convert an inputStream to a URL? Here is my code:
InputStream song1 = this.getClass().getClassLoader().getResourceAsStream("/songs/BrokenAngel.mp3");
URL song1Url = song1.toUrl(); //<- pseudo code
MediaLocator ml = new MediaLocator(song1Url);
Player p;
try {
p = Manager.createPlayer(ml);
p.start();
} catch (NoPlayerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I am not sure you really want to do this. If you need URL for your specific task just do the following:
URL url = this.getClass().getClassLoader().getResource("/songs/BrokenAngel.mp3");
If however you retrieve input stream in one part of you code, then pass it to another module and there want to find what was the source URL for this input stream it is "almost" impossible. The problem is that you get BufferedInputStream that wraps FileInputStream that does not store the information about it source. You cannot retrieve it even using reflection. If you really want to do this you can do the following.
implement you own UrlInputStream extends InputStream the gets into constructor URL, stores it in class varible, creates input stream by invocation of url.openStream() and wraps it.
Now you can use your stream as usual input stream until you have to retrieve the URL. At this point you have to cast it to your UrlInputStream and call getUrl() method that you will implement.
Note that this approach requires the mp3 to be within your application's sub-directory called songs. You can also use relative pathing for the /songs/BrokenAngel.mp3 part (../../ or something like that. But it takes your applications directory as base!
File appDir = new File(System.getProperty("user.dir"));
URI uri = new URI(appDir.toURI()+"/songs/BrokenAngel.mp3");
// just to check if the file exists
File file = new File(uri);
System.out.println(file.exists())
URL song1Url = uri.toURL();
I think what you want is ClassLoader.findResource(String)
That should return a properly formatted jar:// URL. I haven't tested it myself though, so beware
Try this
URI uri = new URI("/songs/BrokenAngel.mp3");
URL song1Url = uri.toURL();
MediaLocator ml = new MediaLocator(song1Url);
Player p;
try {
p = Manager.createPlayer(ml);
p.start();
} catch (NoPlayerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try this
InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();

Check if file exists from string

This is the code I use when I try to read some specific text in a *.txt file:
public void readFromFile(String filename, JTable table) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String a,b,c,d;
for(int i=0; i<3; i++)
{
a = bufferedReader.readLine();
b = bufferedReader.readLine();
c = bufferedReader.readLine();
d = bufferedReader.readLine();
table.setValueAt(a, i, 0);
table.setValueAt(b, i, 1);
table.setValueAt(c, i, 2);
table.setValueAt(d, i, 3);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the reader
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
And it is called in this way:
readFromFile("C:/data/datafile.txt", table1)
The problem is the following: the 1st time I open the program the *.txt file I'm going to read does not exist, so I thought I could use the function exists(). I have no idea about what to do, but I tried this:
if(("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1)
}
It is not working because NetBeans gives me a lot of errors. How could I fix this?
String has no method named exists() (and even if it did it would not do what you require), which will be the cause of the errors reported by the IDE.
Create an instance of File and invoke exists() on the File instance:
if (new File("C:/data/datafile.txt").exists())
{
}
Note: This answer use classes that aren't available on a version less than Java 7.
The method exists() for the object String doesn't exist. See the String documentation for more information. If you want to check if a file exist base on a path you should use Path with Files to verify the existence of the file.
Path file = Paths.get("C:/data/datafile.txt");
if(Files.exists(file)){
//your code here
}
Some tutorial about the Path class : Oracle tutorial
And a blog post about How to manipulate files in Java 7
Suggestion for your code:
I'll point to you the tutorial about try-with-resources as it could be useful to you. I also want to bring your attention on Files#readAllLines as it could help you reduce the code for the reading operation. Based on this method you could use a for-each loop to add all the lines of the file on your JTable.
you can use this code to check if the file exist
Using java.io.File
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
You need to give it an actual File object. You're on the right track, but NetBeans (and java, for that matter) has no idea what '("C:/data/datafile.txt")' is.
What you probably wanted to do there was create a java.io.File object using that string as the argument, like so:
File file = new File ("C:/data/datafile.txt");
if (file.exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
Also, you were missing a semicolon at the end of the readFromFile call. Im not sure if that is just a typo, but you'll want to check on that as well.
If you know you're only ever using this File object just to check existence, you could also do:
if (new File("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
If you want to ensure that you can read from the file, it might even be appropriate to use:
if(new File("C:/data/datafile.txt").canRead()){
...
}
as a condition, in order to verify that the file exists and you have sufficient permissions to read from the file.
Link to canRead() javadoc

How to read/write String from/to .txt?

I've got some text in a text file. I want to read it from file (first string - first line in file etc.), do something with it and then write to another text file.
How to do it?
Apache Commons IOUtils:
String contents = FileUtils.readFileToString(file, "UTF-8");
FileUtils.writeStringToFile(file, contents, "UTF-8");
And the best way to find out how that is done internally (in case you are interested) is to look at the source code for these two methods.
java.util.Scanner -> use this for reading content from file(there are lots of other ways as mentioned by others,but i find this one the simplest.)
java.io.PrintWriter -> use for writing into file(other ways also possible,as mentioned above)
You exactly have to do what other folks have mentioned. But here I will be bit detailed and provide you with some code sample.
To open and read the file:
String fileName = "paper.txt"; // file to be opened
try {
Scanner fileData = new Scanner(new File(fileName));
while(fileData.hasNextLine()){
String line = fileData.nextLine();
line = line.trim();
if("".equals(line)){
continue;
} // end if
} // end while
fileData.close(); // close file
} // end try
catch (FileNotFoundException e) {
// Error message
} // end catch
To write to the text file you can use the following code:
boolean fileOpened = true;
try {
PrintWriter toFile = new PrintWriter("paper.txt");
} // end try
catch (FileNotFoundException e) {
fileOpened = false;
// Error Message saying file could not be opened
} // end catch
if(fileOpened){
toFile.println("String to be added to the file");
toFile.close();
} // end if
I hope this will help you out to solve your problem.

How can I read and print a file in eclipse with relative paths?

I'm trying to read a file in eclipse and print it. The problem is that the compiler always says to me that the file or directory doesn't exist. I have to use relative paths.
The relevant part of the project routes is:
uva.pfc.refactoringEngine.core <--Project
...
src
uva.pfc.refactoringengine.core.actions <-- Actual Package
...
CreateEnumSetPlusClas.java <--File from I want to read the EnumSetPlus.java file
...
EnumSetPlus.java <-- File I want read and print
This is the code:
String total="";
File actual = new File("src/EnumSetPlus.java");
FileReader filereader = null;
try {
filereader = new FileReader(actual);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
BufferedReader input = new BufferedReader(filereader);
try {
while ((line = input.readLine()) != null)
{
total += line + "\n";
}
input.close();
}
catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
System.out.println(total);
I think the problem is that I have to do something if I want the file path recognised by de eclipse project.
Could you help me??
Thaks beforehand.
I'd use getClass().getResourceAsStream("/EnumSetPlus.txt") - this will look for the file on the root of the classpath (which is bin/, but all files from src go to bin). You then get an InputStream which you can adapt to Redaer via new InputStreamReader(stream, encoding)
In Eclipse the current working directory is src by default.
Try this
File actual = new File("EnumSetPlus.txt");
Also I would look into Kevin's answer too. :-)
Try:
String filePath = "/EnumSetPlus.java";
File actual = new File(ClassLoader.getSystemResource(filePath).getFile());
Your example says that you want to read a file called EnumSetPlus.java but the source code is looking for a file called EnumSetPlus.txt.

Categories

Resources