Difference between revisions of "Converting between a URL and a filename path"

From CodeCodex

m (render a specific)
m (Reverted edits by Noemistegman (talk) to last revision by 64.81.53.80)
 
Line 1: Line 1:
 
{{Infobox See Also String}}
 
{{Infobox See Also String}}
スピリチュアル
+
==Implementations==
 +
===Java===
 +
<pre class="java">
 +
    //Create a file object
 +
    File file = new File("filename");
 +
   
 +
    // Convert the file object to a URL
 +
    URL url = null;
 +
    try {
 +
        // The file need not exist. It is made into an absolute path
 +
        // by prefixing the current working directory
 +
        url = file.toURL();          // file:/d:/almanac1.4/java.io/filename
 +
    } catch (MalformedURLException e) {
 +
    }
 +
   
 +
    // Convert the URL to a file object
 +
    file = new File(url.getFile());  // d:/almanac1.4/java.io/filename
 +
   
 +
    // Read the file contents using the URL
 +
    try {
 +
        // Open an input stream
 +
        InputStream is = url.openStream();
 +
   
 +
        // Read from is
 +
        is.close();
 +
    } catch (IOException e) {
 +
        // Could not open the file
 +
    }
 +
</pre>
  
 +
* Original Source: [http://javaalmanac.com/egs/java.io/File2Uri.html]
  
 +
===Perl===
 +
<pre class="perl">
 +
use URI qw(); # GELLER
 +
print URI->new('file:///var/spoon/mail')->file;
 +
</pre>
  
サイキック/スピリチュアルカウンセラーのキャンデスによる、スピリチュアルなDNAアクティベーション。人生が変わり始めます。
+
===Python===
 +
<pre class="python">
 +
import urllib
 +
 +
pathname = 'path/to/file/or/folder/'
 +
url = urllib.pathname2url(pathname)
 +
pathname = urllib.url2pathname(url)
 +
</pre>
 +
 
 +
 
 +
[[Category:Java]]
 +
[[Category:Perl]]
 +
[[Category:Python]]
 +
 
 +
[[Category:I/O]]
 +
[[Category:String]]

Latest revision as of 21:38, 4 September 2012

Related content:

Implementations[edit]

Java[edit]

    //Create a file object
    File file = new File("filename");
    
    // Convert the file object to a URL
    URL url = null;
    try {
        // The file need not exist. It is made into an absolute path
        // by prefixing the current working directory
        url = file.toURL();          // file:/d:/almanac1.4/java.io/filename
    } catch (MalformedURLException e) {
    }
    
    // Convert the URL to a file object
    file = new File(url.getFile());  // d:/almanac1.4/java.io/filename
    
    // Read the file contents using the URL
    try {
        // Open an input stream
        InputStream is = url.openStream();
    
        // Read from is
        is.close();
    } catch (IOException e) {
        // Could not open the file
    }
  • Original Source: [1]

Perl[edit]

use URI qw(); # GELLER
print URI->new('file:///var/spoon/mail')->file;

Python[edit]

 import urllib
 
 pathname = 'path/to/file/or/folder/'
 url = urllib.pathname2url(pathname)
 pathname = urllib.url2pathname(url)