Monday 5 August 2013

Top Most File Handling All Examples :)

1) Create File on location given by you on any operating system.


package com.myapp.filehandling;

import java.io.File;
import java.io.IOException;

public class CreateFile {
public static void main(String[] args) {
// give the path where you want to create file
File file = new File("d:\\newfile.txt");

try {
// file.createNewFile() create new file on location given by you and
// return true if created successfully else throws exception
// IOException
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


2)Reading and Writing Byte by Byte.

package com.myapp.filehandling;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ReaderWriterClassExample {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;

try {
inputStream = new FileReader("d:\\oldfile.txt");
outputStream = new FileWriter("e:\\newfile.txt");

int c;
long starttime = System.currentTimeMillis();
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
long endtime = System.currentTimeMillis();
// This take too much time because of byte by byte reading and then
// writing each time accessing file for reading and then write to
// file is expensive so use BufferReader PrintWriter for fast
// reading and writing
System.out.println(endtime - starttime);

} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}


3) Fast reading from and writing to file.

package com.myapp.filehandling;

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

public class BufferReaderPrintWriterExample {
public static void main(String[] args) throws IOException {

BufferedReader inputStream = null;
PrintWriter outputStream = null;

try {
inputStream = new BufferedReader(new FileReader("d:\\oldfile.txt"));
outputStream = new PrintWriter(new FileWriter("e:\\newfile.txt"));

String l;
long starttime = System.currentTimeMillis();
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
long endtime = System.currentTimeMillis();

// this take hardly one milisec to execute file reading and writing
// so use this classes always
System.out.println(endtime - starttime);
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}


4) Create File depends on operating system.

package com.myapp.filehandling;

import java.io.File;
import java.io.IOException;

public class CreateFileAsOperatingSystem {
public static void main(String[] args) {
try {

String filename = "testing.txt";
String finalfile = "";
// below line of code give you directory where your program executes
String workingDir = System.getProperty("user.dir");
// below system property give you operating system name
String your_os = System.getProperty("os.name").toLowerCase();
if (your_os.indexOf("win") >= 0) {// windows
finalfile = workingDir + "\\" + filename;
} else if (your_os.indexOf("nix") >= 0// unix
|| your_os.indexOf("nux") >= 0) {// linux
finalfile = workingDir + "/" + filename;
} else {
finalfile = workingDir + "{others}" + filename;
}

System.out.println("Final filepath : " + finalfile);
File file = new File(finalfile);

if (file.createNewFile()) {
System.out.println("Done");
} else {
System.out.println("File already exists!");
}

} catch (IOException e) {
e.printStackTrace();
}
}
}

5)Create File without knowing your operating system.

package com.myapp.filehandling;

import java.io.File;
import java.io.IOException;

public class CreateFileWithFileSepaerator {
public static void main(String[] args) {
try {

String filename = "testing1.txt";
String myFile = "";
String workingDir = System.getProperty("user.dir");
// File.Seperator give you slash according to your operating system
// you no need to get operating system and then define your own
// seperator with this property
myFile = workingDir + File.separator + filename;

System.out.println("Final filepath : " + myFile);
File file = new File(myFile);

if (file.createNewFile()) {
System.out.println("Done");
} else {
System.out.println("File already exists!");
}

} catch (IOException e) {
e.printStackTrace();
}
}
}
6) Know about you file details?

package com.myapp.filehandling;

import java.io.File;
import java.io.IOException;

public class FilePermissionExample {
public static void main( String[] args )
    {
    try {
    String filename = "testing1.txt";
    String finalfile = "";
     String workingDir = System.getProperty("user.dir");
 
     finalfile = workingDir + File.separator + filename;
 
     System.out.println("Final filepath : " + finalfile);
 
     File file = new File(finalfile);
 
     if(file.exists()){
     System.out.println("Is Execute allow : " + file.canExecute());
     System.out.println("Is Write allow : " + file.canWrite());
     System.out.println("Is Read allow : " + file.canRead());
     }
 
     file.setExecutable(false);
     file.setReadable(false);
     file.setWritable(false);
 
     System.out.println("Is Execute allow : " + file.canExecute());
     System.out.println("Is Write allow : " + file.canWrite());
     System.out.println("Is Read allow : " + file.canRead());
 
     if (file.createNewFile()){
       System.out.println("File is created!");
     }else{
       System.out.println("File already exists.");
     }
 
    } catch (IOException e) {
     e.printStackTrace();
   }
    }
}


LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt