2013-08-03

Using Java to open and read a file using File Path and File URL

urlstring = "file:///C:/Users/surfer/Desktop/My%20Files/datafiles/DomesticInterestRates.csv"
is the full url to a file DomesticInterestRates.csv on my windows desktop

The Windows path to the same file is
C:\Users\surfer\Desktop\My Files\datafiles\DomesticInterestRates.csv

However, the backslash needs to be escaped as \\ in Java so in order to
open this file in Java I would have to use

"C:\\Users\\surfer\\Desktop\\My Files\\datafiles\\DomesticInterestRates.csv"


File f = new File("C:\\Users\\surfer\\Desktop\\My Files\\datafiles\\DomesticInterestRates.csv");

We can also use a URI to open a file.
The url to the file can be converted into an URI by using
new java.net.URL(urlstring).toURI()



FilesExample.java
 1 package example;
 2 
 3 import java.io.*;
 4 import java.net.*;
 5 
 6 public class FilesExample {
 7 
 8     public static void main(String[] args) {
 9         String filepath = 
10                 "C:\\Users\\surfer\\Desktop\\My Files"+
11                 "\\datafiles\\DomesticInterestRates.csv";
12 
13         String fileurl =
14                 "file:///C:/Users/surfer/Desktop/My%20Files/"+
15                 "datafiles/DomesticInterestRates.csv";
16         
17         // using windows path
18         readfile(filepath);
19         
20         try {
21             // using URI
22             readfile(new URL(fileurl).toURI());            
23         } catch (Exception e) {
24         }
25         
26     }
27 
28     public static void readfile(String filename) {
29         
30         try {
31             File f = new File(filename);
32             BufferedReader in = new BufferedReader(
33                 new FileReader(f) );
34             String line = in.readLine();
35             while ( line != null ) {
36                 System.out.println(line);
37                 line = in.readLine();
38             }
39             in.close();
40         } catch (Exception e) {
41         }
42     }
43     
44     public static void readfile(URI fileuri) {
45         
46         try {
47             File f = new File(fileuri);
48             BufferedReader in = new BufferedReader(
49                 new FileReader(f) );
50             String line = in.readLine();
51             while ( line != null ) {
52                 System.out.println(line);
53                 line = in.readLine();
54             }
55             in.close();
56         } catch (Exception e) {
57         }
58     }
59 }
60 

No comments:

Post a Comment

Github CoPilot Alternatives (VSCode extensions)

https://www.tabnine.com/blog/github-copilot-alternatives/