How to read local and remote file in Java?

 

In our earlier tutorial we have seen list of various file operations. In this tutorial we will see how to read a file from local path and from remote server. Reading files from local and from other server through HTTP will vary. Lets see both examples separately.

Reading from local path:


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
 public static void main(String[] args) {
  
  String fName = "/var/javadiscover/test.txt";
  BufferedReader br = null;
  try {
   FileReader myFile = new FileReader(fName);
   br = new BufferedReader(myFile);
   String line = null;
   while ((line = br.readLine()) != null) {
    System.out.println(line);
   }
  } catch (IOException e) {
   e.printStackTrace();
  
  } finally {
   if (br != null){
    try {
     br.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}



Reading from remote server through HTTP:


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class ReadFile {
 public static void main(String[] args) {
  InputStreamReader isr  = null;
  BufferedReader buffRead = null;
  
  try{
   String fName = "http://mydomain/test.txt";
   URL url  = new URL(fName);
   URLConnection conn  = url.openConnection();
   isr   = new InputStreamReader(conn.getInputStream());
   buffRead  = new BufferedReader(isr);
   String str = "";
   while ((str = buffRead.readLine()) != null) {
    System.out.println(str);    
   }     
  
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  
  } finally{
   try{
    if(buffRead != null) buffRead.close();
    if(isr != null) isr.close();
   }catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}





No comments:
Write comments