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

Thursday, August 20, 2009

Java Source Code to lock a file

Below source code is the simple example of how to lock a file. The below program will not allow you to delete the created file or to edit the created file for 1 min. I will use FileChannel and FileLock class to achieve that.

API Source:

http://java.sun.com/javase/6/docs/api/java/nio/channels/FileLock.html
http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

/**
*
* @author Snehanshu
*/
public class FileLockDemo {

/** Creates a new instance of FileLockDemo */
FileLockDemo() {
}

private void doLockFile() {
try{
File file = new File("./FileLockDemo.txt");
FileLock lock = null;
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write("File is being locked");
bufferedWriter.close();

FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
System.out.println("Locking the file");
lock = channel.lock(0, Long.MAX_VALUE, true); // Create a shared lock on the file.

// This section of code will lock the file for 1 mins [60 secs = 60000 milliseconds].
//For those 60 secs, you will not be able to delete or save the file after editing.
System.out.println("Wait for 60 secs for the program to unlock the file");
try {
Thread.sleep(60000);
} catch (InterruptedException ie) {
ie.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Releasing the lock of the file");
if (lock != null && lock.isValid()) {
lock.release(); // Lock is being released
}
} catch(FileNotFoundException fNFE) {
fNFE.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
FileLockDemo fileLockDemo = new FileLockDemo();
fileLockDemo.doLockFile();
}

}

Delete a file only when it is closed

Hi, below is the code which will create and open a file using window resources and if the file is already created then it will open the file.

try {
Process pc = Runtime.getRuntime().exec("C:/WINDOWS/ServicePackFiles/i386/notepad.exe C:/CheckDemo.txt");
} catch (IOException ex) {
ex.printStackTrace();
}

However I was wondering, if we need to open the file in temporary mode; meaning when the file is closed, it should be automatically deleted.

The waitFor() method of the Process class will do the trick.

The API describes the method like below:

causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

[Source: http://java.sun.com/javase/6/docs/api/java/lang/Process.html]

The code is like below:

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

public class Test {
public static void main(String[] args) throws Exception {
try {
Process pc = Runtime.getRuntime().exec("C:/WINDOWS/ServicePackFiles/i386/notepad.exe C:/CheckDemo.txt");
try {
pc.waitFor();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
File file = new File("C:/CheckDemo.txt");
file.delete();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Tuesday, July 7, 2009

Source Code to write into a file-Java

In this section, I will give you the code how to write into the file using all possible classes of the java.io package.


The classes I am using here are:

BufferWriter, BufferedOutputStream, OutputStream, DataOutputStream, FileWriter, FileOutputStream,PrintWriter, PrintStream.


The below code tells you all possible way of writing into the file using the above classes.

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.io.Writer;
import java.io.File;

public class FileWrite {

/** Creates a new instance of FileWrite */
public FileWrite() {
}
String stringTobeWritten = "This is line to be written";

private void writeBufferWriter(){
try{
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("ReadMeBufferedWriter.txt",true));
bufferedWriter.write(stringTobeWritten);
bufferedWriter.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}


private void writeBufferedOutputStream(){
try{
BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream("ReadMeBufferedOutputStream.txt"));
bufferedOutput.write(stringTobeWritten.getBytes());
bufferedOutput.write("\n".getBytes());
bufferedOutput.write(65); // the byte representation [Ascii code] of 'A'
bufferedOutput.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}


private void writeOutputStream(){
try{
FileOutputStream fos = new FileOutputStream("ReadMeFileOutputStream.txt");
Writer out = new OutputStreamWriter(fos,"UTF8");
out.write(stringTobeWritten);
out.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}



private void writeDataOutputStream(){
try{
FileOutputStream fos = new FileOutputStream("ReadMeDataOutputStream.txt");
DataOutputStream dos = new DataOutputStream(fos);
int ch = 65;
dos.writeChar(ch); // Writing Character ascii of A
dos.writeBytes(stringTobeWritten); // writing string
dos.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}



private void writeFileWriter(){
try{
FileWriter fw = new FileWriter("ReadMeFileWriter.txt");
fw.write(stringTobeWritten+"\n");
fw.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}


private void writeFileOutputStream(){
try{
FileOutputStream fos = new FileOutputStream("ReadMeFileOutputStream.txt");
fos.write(stringTobeWritten.getBytes());
fos.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}

private void writePrintWriter(){
try{
PrintWriter printWriter = new PrintWriter("ReadMePrintWriter.txt");
printWriter.write(stringTobeWritten);
printWriter.write(stringTobeWritten.toCharArray()); // Character Array
printWriter.write("\n");
printWriter.write('C'); //Character
printWriter.write(65); // Ascii of 'A'
printWriter.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}


private void writePrintStream(){
try{
File file = new File("ReadMePrintStream.txt");
PrintStream p = new PrintStream(new FileOutputStream(file, false));
p.println(stringTobeWritten);
p.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}



public static void main(String argd[]) {
FileWrite fileWriter = new FileWrite();
fileWriter.writeBufferWriter();
fileWriter.writeBufferedOutputStream();
fileWriter.writeOutputStream();
fileWriter.writeDataOutputStream();
fileWriter.writeFileWriter();
fileWriter.writeFileOutputStream();
fileWriter.writePrintWriter();
fileWriter.writePrintStream();
}

}


Any suggestions/feedback appreciated.

Monday, July 6, 2009

Java Source code to extract the disk space status for drives

JDK 1.6 introduces new functionalities to extract the disk space status for a particular drive. Check it out.


The following program will list out the details of the status for a particular drive.

/*
Class to deal with disk spaces
JDK 1.6 Compatible
*/

import java.io.File;
import java.text.DecimalFormat;

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

File file = new File("D:\\");
DecimalFormat df = new DecimalFormat("##.##");

long totalSpace = file.getTotalSpace();
long usableSpace = file.getUsableSpace();
long freeSpace = file.getFreeSpace();

File drives[] = File.listRoots();

System.out.println("The drives available are: ");

// Loop through the drive list and display the drives.
for (int index = 0; index < drives.length; index++) {
System.out.println(drives[index]);
}

// Convert it to GigaBytes
double valueGBTotalSpace = (double) totalSpace / 1024 / 1024 / 1024;
double valueGBUsableSpace = (double) usableSpace/ 1024 / 1024 / 1024;
double valueGBFreeSpace = (double) freeSpace/ 1024 / 1024 / 1024;
double valueGBUsedSpace = (double) (totalSpace - freeSpace)/ 1024 / 1024 / 1024;



System.out.println("Total space in " + file + " partition is "+df.format(valueGBTotalSpace));
System.out.println("Total Usable space available in " + file + " partition is "+df.format(valueGBUsableSpace));
System.out.println("Total Free space available in " + file + " partition is "+df.format(valueGBFreeSpace));
System.out.println("Total Used space available in " + file + " partition is "+df.format(valueGBUsedSpace));
}
}


Hope you all will find it useful.

Java Source Code for extracting the folder and file details of a given drive/folder

Hi,


Today I am going to tell you the source code for extracting the each and every details of the files and folder of a given folder. Like in C:\ drive contains many folder as well as files; the folder in turn contains the files too. The below program will list out the details of all that files and folder.


Note: If you try to do it with C:\ drive, it might take longer time to complete the process as for most of the cases, it will contain Program Files, which itself contains thousands of the files and folders.


The source code as follows:

import java.io.File;

public class FileDetails {

FileDetails() {

}

private static void getFileDetails(File folder) {
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File under " + folder + " -> " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory under " + folder + " -> " + listOfFiles[i].getName());
getFileDetails(listOfFiles[i]); // Recursive call of the directory to find out the files under that
}
}
}

public static void main(String[] args) {
FileDetails fileDetails = new FileDetails();
String directory = new String("C://");
File folder = new File(directory);
fileDetails.getFileDetails(folder);
}
}

Wednesday, June 10, 2009

To zip a file or folder using java

This article tells you the simple code to zip a file or folder. We are going to use ZipEntry and ZipOutputStream to zip the file.

The codes are as follows:

To zip a file:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.util.zip.ZipEntry;
import java.io.File;
import java.util.StringTokenizer;
import java.text.SimpleDateFormat;
import java.io.InputStream;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.zip.Deflater;

public class ZipFileZip {

ZipFileZip(){

}

public static void main(String args[]){
ZipFileZip zipFileZip = new ZipFileZip();
zipFileZip.doZipFile("Sample.txt");
}


private void doZipFile(String fileSource){
File file = new File(fileSource);
if(!file.isDirectory()){
System.out.println("A File");
String extn = fileSource.substring(fileSource.lastIndexOf(".")+1);
String zipFileDest = new String();
zipFileDest = "./HouseKeep/"+fileSource.substring(fileSource.lastIndexOf("/")+1,fileSource.lastIndexOf("."));
File f = new File(fileSource);
byte[] buffer = new byte[18024];
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileDest+"_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".zip"));
out.setLevel(Deflater.DEFAULT_COMPRESSION);
FileInputStream in = new FileInputStream(fileSource);
out.putNextEntry(new ZipEntry(zipFileDest+"."+extn));
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
in.close();
out.close();
boolean isFileDeleted = f.delete();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
} else {
System.out.println("A File");
}
}

}


TO zip a folder:


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.util.zip.ZipEntry;
import java.io.File;
import java.util.StringTokenizer;
import java.text.SimpleDateFormat;
import java.io.InputStream;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.zip.Deflater;

public class ZipFolder {

ZipFolder(){

}

public static void main(String args[]){
ZipFolder zipFolder = new ZipFolder();
zipFolder.doZipFolder("SampleFolder");
}

private void doZipFolder(String fileSource){
File file = new File(fileSource);
String lastToken = "";
StringTokenizer strToken = new StringTokenizer(fileSource,"/");

while(strToken.hasMoreTokens()){
lastToken = strToken.nextToken();
}
File outFile = new File("./HouseKeep/"+lastToken+"_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".zip");
System.out.println("A directory");
try{
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
BufferedInputStream in =null;
byte[] data = new byte[2048];
String files[] = file.list();
for (int i=0; i < files.length; i++) {
in = new BufferedInputStream(new FileInputStream(file.getPath() + "/" + files[i]),2048);
out.putNextEntry(new ZipEntry(files[i]));
int count;
while((count = in.read(data,0,2048)) != -1){
out.write(data, 0, count);
}
out.closeEntry();
}
out.flush();
out.close();
out.close();
in.close();
}catch(Exception e){
e.printStackTrace();
}
}

}





Thanks all. Hope you all will find it useful.

Total Pageviews