Skip to main content

URL to File?

4 replies [Last post]
pelz
Offline
Joined: 2008-06-08

Is there any possibility for converting the class of "java.net.URL" or "java.net.URLConnection" to class of "java.io.File"?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
walterln
Offline
Joined: 2007-04-17

Using the [url=http://java.sun.com/javase/6/docs/api/java/io/File.html#File(java.net.URI)]URI constructor[/url]:
[code]new File(url.toURI());[/code]

pelz
Offline
Joined: 2008-06-08

Hi walterln!

Thanks for your reply, but it is not good for me, becouse I want to open a file from web. So the URL protocol is not "file:", but "http:".
If I use your solution, my program does not work also good.

This is my program with your solution:

[code]
import com.sun.media.jai.codec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.media.jai.*;
import javax.swing.*;
import java.util.*;

public class FileUrlExampleFrame extends JFrame {
JLabel lab = new JLabel();

public FileUrlExampleFrame() {
super(" File and URL");
setSize(420, 340);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout border = new BorderLayout();
setLayout(border);

try {
URL url = new URL("http://www.biology-blog.com/images/blogs/10-2007/cercidiphyllum-japonicum.jpg");
File inp = new File(url.toURI());
BufferedImage bufIm = ImageIO.read(inp);
Image image = bufIm.getScaledInstance(
400, 320, Image.SCALE_SMOOTH
);
ImageIcon icon = new ImageIcon(image);
lab.setIcon(icon);
add(lab, BorderLayout.CENTER);
}
catch (Exception e) {
e.printStackTrace();
}
setResizable(false);
setVisible(true);
}

}
[/code]

When I run the program, I get the following error message:
[b]
java.lang.IllegalArgumentException: URI scheme is not "file"
at java.io.File.(File.java:366)
at FileUrlExampleFrame.(FileUrlExampleFrame.java:31)
at MainClass.main(MainClass.java:11)[/b]

tarbo
Offline
Joined: 2006-12-18

Why do you want to pass a file when you can pass your URL to [url=http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html#read(java.net.URL)]ImageIO.read[/url] instead?

pelz
Offline
Joined: 2008-06-08

The answer for your question: defect in my knowledge, and it escaped my attention.

So thank you very much! Your solution works very well.