Java convert inputStream to URL - java

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();

Related

File is not readable after file.setReadable(true)

I try to read the file and get FileNotFoundExeption.
File file = new File("News.out");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
try{
in.readObject();
}
I check, that the file really exists in the directory and check "readable" property of the file.
Then I added programmatical setting of "readable" and "writable" properties
file.setReadable(true);
file.setWritable(true);
System.out.println(file.canRead());
System.out.println(file.canWrite());
And got in logs false, false.
What may be the reason of this?
EDIT:
I tried JSR 203 and use this code:
Path path = FileSystems.getDefault().getPath(filename);
try(
final InputStream in = Files.newInputStream(path);
) {
ObjectInputStream objectInputStream = new ObjectInputStream(in);
newsStorage.setEntities((ArrayList<News>) objectInputStream.readObject());
} catch (NoSuchFileException e) {
createFile(path, filename);
handleException(e);
}
And createFile() method:
private void createFile(Path path, String string) {
try {
Files.newOutputStream(path, StandardOpenOption.CREATE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
File was not created.
Do I understand correctly, that
Files.newOutputStream(path, StandardOpenOption.CREATE);
should create a file?
Do yourself a favor and drop File. Use JSR 203 instead.
Try and use:
try (
final InputStream in = Files.newInputStream("News.out");
) {
// work with "in" here
}
If you can't perform the opening then you will at least have an exception telling you what exactly is wrong, something File has never been able to do.
After that, if you want to set permissions on the file, you can also do so with JSR 203 but that depends on the capabilities of the underlying filesystem. If your filesystem is POSIX compatible then you may use this method for instance. But it also may be that you cannot modify the permissions of the file either.

java.nio.file.AccessDeniedException when reading a file

I want to read file content using this code:
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
On some systems this file is not present or it's empty. How I catch this exception? I want to print message "No file" when there is no file and there is no value.
The AccessDeniedException can be thrown only when using the new file API. Use an inputStream to open a stream from the source file so that you could catch that exception.
Try with this code :
try
{
final InputStream in = new Files.newInputStream(Path.get("/sys/devices/virtual/dmi/id/chassis_serial"));
} catch (FileNotFoundException ex) {
System.out.print("File not found");
} catch(AccessDeniedException e) {
System.out.print("File access denied");
}
Try to use filter file.canRead()) to avoid any access exceptions.
Create a File object and check if it exists.
If it does then it's safe to convert that file to a byte array and check that the size is greater then 0. If it is convert it to a String. I added some sample code below.
File myFile = new File("/sys/devices/virtual/dmi/id/chassis_serial");
byte[] fileBytes;
String content = "";
if(myFile.exists()) {
fileBytes = File.readAllBytes(myfile.toPath);
if(fileBytes.length > 0) content = new String(fileBytes);
else System.out.println("No file");
else System.out.println("No file");
I know it's not the one liner you were looking for. Another option is just to do
try {
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
} catch(Exception e) {
System.out.print("No file exists");
}
Read up on try catch blocks here like MrTux suggested, as well as java Files and java io here.

Get file to be read from another package

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

How to describe content of file rar / zip in jtable from url or path(directory)?

How to describe content of file rar/zip in jtable from url or path directory in java?
I found here and here
But how to open from URL on describe to jtable?
I'd use PrpcessBuilder, shown here, to execute unzip -l or unrar -l and parse the output to create my TableModel. See also How to Use Tables.
You need to model the data some how. Maybe a VirtualFile, this should contain the information you want to display.
You then need to create a model of the that wraps this data in some meaningful way. You'll need a TableModel for this purpose (preferably use the Abstract or Default implementation)
Once you've decided on how you want the model to be laid out, you simply supply the modle to the JTable
For more information check out How to use Tables
UPDATE
You can learn more from the Basic I/O lesson, but here's a (really) basic example of reading the contents of URL to local disk
File outputFile = new File("Somefile on disk.rar");
Inputstream is;
OutputStream os;
try {
is = url.openStream();
os = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesIn = -1;
while ((bytesIn = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesIn);
}
os.flush();
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
is.close();
} catch (Exception exp) {
}
try {
os.close();
} catch (Exception exp) {
}
}

How to convert InputStream to FileInputStream

I have this line in my program :
InputStream Resource_InputStream=this.getClass().getClassLoader().getResourceAsStream("Resource_Name");
But how can I get FileInputStream from it [Resource_InputStream] ?
Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.
Long story short:
Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.
You need something like:
URL resource = this.getClass().getResource("/path/to/resource.res");
File is = null;
try {
is = new File(resource.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream input = new FileInputStream(is);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

Categories

Resources