Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

Change file permission using java

 
Changing file permission using GUI is an end user easy operation. Same thing if we need to change multiple files like around hundreds or thousands of file then its difficult. But we can achieve this easy by using Java code. So lets see simple example for reading file permissions and then changing file to full permission (Read, Write and Execute).
Change file permission using java



import java.io.File;

public class FilePermissionTest {

 public static void main(String[] args) {
  
  String testFile = "D://testfile.txt";
  
  File file = new File(testFile);
  System.out.println("Current File Permissions : ");
  System.out.println("\t Read     : "+file.canRead());
  System.out.println("\t Write    : "+file.canWrite());
  System.out.println("\t Execute  : "+file.canExecute());
  
  System.out.println("\nLets change file to full permission ");
  
  file.setReadable(true);
  file.setWritable(true);
  file.setExecutable(true);
  
  System.out.println("\nChanged File Permissions : ");
  System.out.println("\t Read     : "+file.canRead());
  System.out.println("\t Write    : "+file.canWrite());
  System.out.println("\t Execute  : "+file.canExecute());
 }
}

OUTPUT:


Current File Permissions : 
  Read     : true
  Write    : false
  Execute  : true

Lets change file to full permission 

Changed File Permissions : 
  Read     : true
  Write    : true
  Execute  : true

How to read webpage source code through Java?

We might be seeing "view page source" option in all web browsers. Just by right click and by selecting "view page source" it will give us the complete client side source code of that particular page. So how we can get this done by using Java code? For this we need to use URLConnection class which establish the connection to the server and next by using InputStream class we can read complete page content as bytes. 

Next by iterating InputStream instance (byte by byte) we can get the complete page source as bytes and we can store it in a file for our reference. Lets see simple example to read web page source code through Java.


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class URLReader {
 
 public static void main(String[] args) {
  try{
   URL url = new URL("http://docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html");
   URLConnection urlCon = url.openConnection();
   InputStream is = urlCon.getInputStream();
   
   File myFile = new File("C://URLConnection.html");
   if(!(myFile.exists())){ 
             myFile.createNewFile();
   }
   
   FileWriter fWrite = new FileWriter(myFile, true);  
         BufferedWriter bWrite = new BufferedWriter(fWrite); 
   int i=0;
   while((i=is.read()) != -1){
       bWrite.write((char)i); 
   }

   bWrite.close();
   System.out.println("Web page reading completed...");
   
  }catch (Exception e) {
   e.printStackTrace();
  } 
  
 }
}


OUTPUT:
read webpage source code through Java

read webpage source code through Java



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





How to Create, Write/Append, Read, Delete and Rename a file in Java?

 


We can see in all applications and programs we may need to write or edit file. File operations like creating, deleting, append etc., So in this tutorial we will see about Create, Write, Read and Delete a file using Java code. Each file operations we will discuss with separate program and lets see the output. 
NOTE: File name, path and folder names can vary accordingly. 


1. How to create a file in Java?


public class CreateFile {
    public static void main(String[] args) {
        File myFile = new File("javadiscover.txt");
        try{
        if(!(myFile.exists())){ // checking file exist or not
            myFile.createNewFile(); // Creating new file
            System.out.println("New File created....");
        }else{
            System.out.println("File already exisit....");
        }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}



OUTPUT:


New File created....




2. How to Write/ Append a text into a file in Java ?

public class WriteFile {
    public static void main(String[] args) {
        
        FileWriter fWrite = null;
        BufferedWriter bWrite = null;
        
        String content = "Hi All, Welcome to Java Discover";
        File myFile = new File("javadiscover.txt");
        
        try{
            if(!(myFile.exists())){
                myFile.createNewFile();
        }
        fWrite = new FileWriter(myFile, true); // true for appending content to the existing file
            bWrite = new BufferedWriter(fWrite);
            bWrite.write(content);
            bWrite.close();
            
            System.out.println("File write complete.....");
            
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fWrite != null
                try { fWrite.close(); } catch (IOException e) { e.printStackTrace(); }
            if(bWrite != null
                try { bWrite.close(); } catch (IOException e) { e.printStackTrace(); }            
        }
    }
}



OUTPUT:

Console

File write complete.....


File


3. How to read a file in Java ?


public class ReadFile {
    public static void main(String[] args) {
        BufferedReader br = null;
        try{
            FileReader myFile  = new FileReader("javadiscover.txt");
            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();}
        }        
    }
}


OUTPUT:


Hi All, Welcome to Java Discover
Blog about Java questions and answers


4. How to delete a file in Java ?



public class DeleteFile {
    public static void main(String[] args) {
        try{
            File myFile = new File("javadiscover.txt");
            if(myFile.exists()){
                myFile.delete();
                System.out.println("File deleted successfully....");
            }else{
                System.out.println("File NOT Exisit....");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}



OUTPUT:


File deleted successfully....





5. How to rename a file in Java ?

public class RenameFile {
    public static void main(String[] args) {
        File oriFile = new File("java.txt");
        File newFile = new File("javadiscover.txt");
        if(oriFile.exists()){
            oriFile.renameTo(newFile);
            System.out.println("File rename completed....");
        }else{
            System.out.println("Original file not exist for renaming....");
        }
    }
}



OUTPUT:


File rename completed....





Apart from these examples various file operations which you can refer to Oracle docs.