Showing posts with label Java file tutorials. Show all posts
Showing posts with label Java file tutorials. Show all posts

Friday, November 22, 2019

How To Practise A Zilch File Inward Java? Zipentry Together With Zipoutputstream Compression Example

Since compressing together with archiving erstwhile log file is an essential housekeeping task inwards whatever Java application environment, a Java programmer should know how to compress files inwards .zip format together with thus how to read them programmatically if required. The JDK provides total back upward to practice together with read ZIP files inwards Java. There is a split parcel java.util.zip to concord all classes related zipping together with unzipping files together with streams. In this serial of article, y'all volition larn how to usage those classes e.g. ZipFile, ZipEntry, ZipInputStream, together with ZipOutputStream etc. This is the mo article almost how to piece of occupation amongst compressed archives inwards Java e.g. .zip files. In the final article, I induce got shown y'all how to read ZIP archives inwards Java together with today, I'll learn y'all how to compress files inwards the ZIP file format past times yourself using a Java program. You volition compress a bunch of text file to practice a .zip file past times using JDK's ZIP file back upward classes.

You practice a .zip file inwards Java to archive files together with directory inwards the compressed format. The JDK (Java Development Kit) provides necessary classes to brand a nix file inwards java.util.zip package. You instance usage ZipEntry, ZipFile, together with ZipOutputStream classes to compress files together with practice a nix archive. But earlier that, let's unopen to of import classes together with their functions.

  • java.util.zip.ZipFile - This degree is used to read entries from a nix file. 
  • java.util.zip.ZipEntry - This degree is used to stand upward for a ZIP file entry.
  • java.util.zip.ZipInputStream - This degree implements an input current filter for reading files inwards the ZIP file format. Includes back upward for both compressed together with uncompressed entries.
  • java.util.zip.ZipOutPutStream - This degree implements an output current filter for writing files inwards the ZIP file format. Includes back upward for both compressed together with uncompressed entries.

Btw, the java.util.zip parcel non alone provides classes to read together with write files compressed inwards ZIP format, but also classes to read/write GZIP format classes every bit good e.g. GZIPInputStream together with GZIPOutputStream. We'll larn almost them inwards unopen to upcoming tutorials. If y'all are curious almost them but at i time thus reading Core Java For The Impatient past times Cay S. Horstmann.


Unlike at that topographic point were two ways to read ZIP file inwards Java e.g. past times using ZipInputStream together with ZipFile, at that topographic point is alone i means to practice Zip file inwards Java i.e. past times using ZipOutputStream. This degree writes information to an output current inwards the ZIP file format. If y'all desire to shop information inwards a file, y'all must chain ZipOutputStream to a FileOutputStream, similar to what nosotros practice inwards Decorator pattern.

Once y'all practice the nix output stream, the adjacent mensuration volition hold out to opened upward rootage text files which y'all desire to compress. You induce got to practice a nix entry for each file using the java.util.zip.ZipEntry degree together with earlier y'all write the information to stream, y'all must outset pose the nix entry object using the putNextEntry() method of ZipOutputStream. Once this is done, y'all tin write the information together with unopen the stream.

So, these were the 3 steps y'all demand to follow to compress a text file together with practice a ZIP file inwards Java i.e.
  1. Create a FileOutputStream to practice nix file
  2. Pass that FileOutputStream to ZipOutputStream to write information inwards zipping file format. 
  3. Optionally y'all tin wrap FileOutputStream into BufferedOutputStream for ameliorate write performance.
  4. Open each rootage file using File class
  5. Create a ZipEntry past times using those File objects
  6. Put the ZipEntry into ZipOutputStream using putNextEntry() method
  7. write the information to the ZIP file using write() method of ZipOutputStream.
  8. close the stream

We'll meet the consummate code representative of creating a nix file inwards Java inwards adjacent department to meet these steps inwards action.




How to Create a Zip file inwards Java Code

Here is our consummate Java programme to parcel files inwards a ZIP file inwards Java. In this program, nosotros induce got a brace of text files together with a directory amongst a file inwards the Eclipse projection directory. We'll compress those files together with directory to practice a compressed file inwards ZIP file format. You tin usage this file similar to the .zip file created WinZip or WinRAR utility which archives files using ZIP format. You tin fifty-fifty opened upward them using whatever nix tool e.g. Winzip, WinRAR, or 7Zip etc.

Anyway, hither is the hide shot of the files together with directory which volition hold out compressed to practice a ZIP file inwards Java:
 Since compressing together with archiving erstwhile log file is an essential housekeeping task inwards whatever Java How to practice a ZIP File inwards Java? ZipEntry together with ZipOutputStream Compression Example

The files which volition hold out compressed are names.txt, java7.txt, together with java.txt. I'll also include the directory targetrr, which contains an apache.txt file, but to demonstrate that y'all tin also include subdirectories amongst files field zipping them.  Unfortunately, these files are non large thus y'all won't meet the final result of compression e.g. compressing a 1GB text file to practice a ZIP file inwards KB, but y'all tin practice that yourself. Just re-create the log file y'all desire to compress inwards the archive directory together with run the program.


Java Program to practice ZIP File inwards Java
package demo;  import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;  /**  * Java Program to demonstrate how to practice ZIP file inwards Java. ZIP file contains  * private files inwards compressed format.  *   * @author java67  */  public class FileCopyDemo {      public static void main(String args[]) {          try {             // let's practice a ZIP file to write data             FileOutputStream fos = new FileOutputStream("sample.zip");             ZipOutputStream zipOS = new ZipOutputStream(fos);              String file1 = "names.txt";             String file2 = "java7.txt";             String file3 = "targetrr/apache.txt";             String file4 = "java.txt";              writeToZipFile(file1, zipOS);             writeToZipFile(file2, zipOS);             writeToZipFile(file3, zipOS);             writeToZipFile(file4, zipOS);              zipOS.close();             fos.close();          } catch (FileNotFoundException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }      }      /**      * Add a file into Zip archive inwards Java.      *       * @param fileName      * @param zos      * @throws FileNotFoundException      * @throws IOException      */     public static void writeToZipFile(String path, ZipOutputStream zipStream)             throws FileNotFoundException, IOException {          System.out.println("Writing file : '" + path + "' to nix file");          File aFile = new File(path);         FileInputStream fis = new FileInputStream(aFile);         ZipEntry zipEntry = new ZipEntry(path);         zipStream.putNextEntry(zipEntry);          byte[] bytes = new byte[1024];         int length;         while ((length = fis.read(bytes)) >= 0) {             zipStream.write(bytes, 0, length);         }          zipStream.closeEntry();         fis.close();     } }  Ouput : Writing file : 'names.txt' to nix file Writing file : 'java7.txt' to nix file Writing file : 'targetrr/apache.txt' to nix file Writing file : 'java.txt' to nix file


If y'all opened upward this ZIP file inwards your car using WinZIP or WinRAR y'all tin meet that it contains all 3 files together with the unmarried directory amongst a file nosotros induce got but added, every bit shown below:

 Since compressing together with archiving erstwhile log file is an essential housekeeping task inwards whatever Java How to practice a ZIP File inwards Java? ZipEntry together with ZipOutputStream Compression Example


Important Points

Some useful of import points related to compression, archiving, together with how to piece of occupation amongst compressed files e.g. ZIP together with GZIP files inwards Java:

1) Compression together with archiving are ii dissimilar things, but inwards Windows tools, similar Winzip does both i.e. they compress the files together with archive them into a split file.

2) In UNIX, y'all induce got to usage split commands for archiving together with compression e.g. tar command is used for archiving together with gzip is used to compress the archived file.

3) Files added to a ZIP/JAR file are compressed individually

4) The JDK back upward both ZIP together with GZIP file formats, It provides classes to read, practice together with alter ZIP together with GZIP file formats. For example,  you tin usage ZipInputStream /ZipOutputStream to read/write ZIP file format together with GZIPInputStream together with GZIPOutputStream to read/write compressed information inwards GZIP file format.


That's all almost how to practice a nix file inwards Java. It's similar to creating a nix file inwards windows past times using the Winzip tool. You tin usage this programme to archive erstwhile log files to salvage unopen to infinite on your Web Server. You tin also lift this programme to induce got the input together with output place i.e. the place to selection files together with where to practice the output files. You tin read to a greater extent than almost compression together with archive inwards Java on Java: How to Program past times Deitel together with Deitel, i of the most consummate books inwards Java, which covers almost everything from inwardness Java to Swing to JDBC.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Saturday, November 9, 2019

How To Lock A File Earlier Writing Inwards Java? Example

Influenza A virus subtype H5N1 file is 1 of the oldest ways to shop information too percentage information exactly if y'all are working inwards a shared file i.e a file which tin locomote read or write yesteryear multiple readers too writers, y'all require to brand certain that the file is locked before y'all test to write on it. This is needed to ensure that individual doesn't overwrite the information y'all are writing. Fortunately, Java provides a machinery to lock a file before writing using the FileLock interface. You tin learn the grip of FileLock yesteryear using FileChannel for writing to a file. The FileChannel degree is mostly used to write faster inwards the large file too 1 of the mutual agency to write binary information inwards Java.

In gild to lock the file before writing, y'all require to telephone band the tryLock() method on FileChannel. This method attempts to learn an exclusive lock on this channel's file. It returns a lock object representing the newly-acquired lock, or null if the lock could non locomote acquired because roughly other programme holds an overlapping lock.

This is a non-blocking method too an invocation e'er returns immediately, either having acquired a lock on the requested part or having failed to practise so. If it fails to learn a lock because an overlapping lock is held yesteryear roughly other programme too so it returns null.

If it fails to learn a lock for whatever other argue too so an appropriate exception is thrown.

For example, It volition throw the OverlappingFileLockException - If a lock that overlaps the requested part is already held yesteryear this Java virtual machine, or if roughly other thread is already blocked inwards this method too is attempting to lock an overlapping part too ClosedChannelException if this channel is closed.

You require to ensure that those exceptions are handled properly too if y'all are non certain why too how to grip exceptions inwards Java, I advise y'all locomote through the Error too Exception department of Complete Java nine Masterclass course of teaching yesteryear Udemy.



Java Program to lock a file before writing

Now that nosotros empathize that nosotros tin piece of occupation FileChannel's tryLock() method too FileLock interface to lock a file before writing, let's run into the programme inwards action. This volition help y'all to empathize the concept better.

import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.concurrent.TimeUnit;  /*  * Java Program to lock a file before writing into it.  */  public class Demo {    public static void main(String[] args) throws Exception {          RandomAccessFile file = new RandomAccessFile("accounts.txt", "rw");     FileChannel channel = file.getChannel();          FileLock lock = null;     try {       lock = channel.tryLock();     } catch (final OverlappingFileLockException e) {       file.close();       channel.close();     }      file.writeChars("writing later lock");     TimeUnit.HOURS.sleep(1);     lock.release();          file.close();     channel.close();    }  }

In this program, nosotros convey created a RandomAccessFile called "accounts.txt" too and so retrieved the FileChannel yesteryear calling the getChannel() method on it. In gild to lock the file before writing into it, nosotros convey called the tryLock() method which volition learn the lock.



After acquiring the lock nosotros write roughly characters into the file too before releasing the lock yesteryear calling lock.release() nosotros made our programme to slumber for 1 sixty minutes using TimeUnit.sleep() method. You tin too piece of occupation the Thread.sleep() method hither exactly I prefer TimeUnit because its explicitly on how much fourth dimension thread is going to wait.

This business office is of import to demonstrate what volition occur if roughly other programme is writing into the file at the same time.

When y'all start run this program, it volition practise an accounts.txt file inwards your projection directory too when y'all opened upwardly the file y'all tin run into the content exactly the programme volition non goal it volition locomote along running because of the slumber nosotros convey position there.

Then nosotros test to run the programme in 1 trial to a greater extent than too at this time, y'all volition run into the next error:

Exception inwards thread "main" java.io.IOException: The procedure cannot access the file because roughly other procedure has locked a portion of the file
at java.io.RandomAccessFile.writeBytes(Native Method)
at java.io.RandomAccessFile.writeChars(RandomAccessFile.java:1123)
at Demo.main(Demo.java:26)


This happens because the before programme hasn't released the lock yet. Remember it was paused before calling the lock.release() method.

This becomes to a greater extent than clear amongst the next screenshot from Eclipse IDE, where y'all tin run into that the before programme is notwithstanding running (instance 1) which locked the file too therefore when y'all run the programme again, it died amongst higher upwardly mistake related to file locking:

 Influenza A virus subtype H5N1 file is 1 of the oldest ways to shop information too percentage information exactly if y'all are working inwards a How to lock a File before writing inwards Java? Example

That's all almost how to lock a file before writing inwards Java. If y'all are non the exclusive author on the file or y'all are working amongst a shared file too so y'all should e'er lock the file before writing information into it. Failing to practise may number inwards file corruption too information loss.

You should too brand certain to unloose the lock in 1 trial y'all are done amongst your writing into the file too render appropriate exception treatment to grab OverlappingFileLockException too IOException.

Other Java too File tutorials y'all may similar to explore
Introduction to Java for Programmers
How to practise a ZIP file inwards Java?
How to write to a file inwards Java?
How to append text into existing file inwards Java?
How to read from an Excel File inwards Java using Apache POI
How to read a text file into ArrayList inwards Java?
Complete Java nine Masterclass yesteryear Udemy

Thanks for reading this article, if y'all similar my explanation of how to lock a file before writing information into it too so delight percentage amongst your friends too colleagues. If y'all convey whatever questions or feedback too so delight driblet a note.

Friday, November 8, 2019

How To Function Amongst Files Too Directories Inwards Java

The File API is 1 of the of import parts of whatever programming linguistic communication or API together with fifty-fifty though Java's file API both novel together with old, are powerful, they are non intuitive plenty compared to other languages e.g. Python. Apart from knowing the essential classes together with abstractions e.g. File, InputStream, OutputStream, Reader, Writer, Channel etc, you lot too quest to know together with retrieve simply about nitty gritty item to avoid subtle issues. There are many articles out at that topographic point on the meshing which tin learn you lot how to read together with write information from the file but at that topographic point are really few which volition tell you lot to produce it inward correct way.

There are things you lot alone acquire when you lot produce meaningful operate e.g. reading/writing information from a existent file together with inward a existent production environs where things similar missing information together with corrupted information together with functioning matter. If you lot receive got expert agreement of basics of File API inward Java hence alone you lot tin write code which tin stand upwards seek of time.

Unfortunately, at that topographic point is no serious majority which volition learn you lot the effective means of file treatment inward Java, at to the lowest degree I don't know, if you lot know delight share. Even Effective Java tertiary Edition doesn't embrace File treatment API, despite roofing most of the stuff.

To start with, I am going to part simply about of the basic materials related to file treatment inward Java, which goes a long means to uncovering together with troubleshoot whatever file related issues inward production.

If you lot receive got been working inward Java for a duet of years together with exposed to the file API hence you lot mightiness already know most of the points together with mayhap you lot tin add together a few to a greater extent than into the listing together with I encourage you lot to produce hence together with part your sense amongst us. There is no amend means of learning than sharing knowledge.

Anyway, without farther ado, hither are simply about of the basics nearly file together with directory treatment inward Java.



10 things  to retrieve piece reading, writing from/to a file inward Java

Here is my listing of 10 essential things Java developer should know nearly File treatment inward Java programming language.  These are mainly basic materials but I was surprised when many programmers never heard nearly it. You mightiness know simply about of these already but if you lot acquire something novel hence don't forget to nation thanks. 

1) The same java.io.File course of education is used to correspond both file together with directory inward Java. You tin role the isDirectory() together with isFile() method from the java.io.File course of education to depository fiscal establishment tally if you lot are genuinely working amongst a file or directory.  See this article to acquire to a greater extent than nearly File together with Directory inward Java.


2) In Java, InputStream is used for reading information together with OutputStream is used for writing data. In the context of a file, FileInputStream is used to read information from a file together with FileOutputStream is used to write information into the file. I know, it's slowly to retrieve that 1 you lot know but I receive got seen many Java programmers struggling amongst InputStream together with OuputStream together with their meaning.


3) Java provides dissimilar classes for dissimilar needs inward java.io package, for example, Stream classes e.g. InputStream together with OutputStream are used to read together with write binary information piece Reader together with Writer e.g. BufferedReader together with BufferedWriter are used to writing grapheme or text data.


4) It is really of import to unopen the current afterward using it, equally it is non closed implicitly, to unloose whatever resources associated amongst it, piece inward the output stream, the close() method calls flush() before releasing the resources which forcefulness whatever buffered bytes to live on written to the stream. See Complete Java ix Masterclass to acquire to a greater extent than nearly how to unopen Stream inward correct way.

 The File API is 1 of the of import parts of whatever programming linguistic communication or API together with fifty-fifty th How to operate amongst Files together with Directories inward Java


5) If nosotros seek to read from a file that doesn’t exist, a FileNotFoundException volition live on thrown but If nosotros seek to write to a file that doesn’t exist, the file volition live on created starting fourth dimension together with no exception volition live on thrown


6) FileReader together with FileWriter classes are used to read/write information from a text file inward Java. Even though you lot tin use FileInputStream and FileOutputStreamFileReader and FileWriter are to a greater extent than efficient together with handles grapheme encoding issues for you. You tin come across the difference betwixt FileReader together with FileInputStream to acquire to a greater extent than nearly that.


7) If you lot are dealing amongst a shared file hence brand certain you lot lock the file earlier writing into it. You tin role the FileLock interface for locking the portion of the file. You tin acquire the associated lock for a file past times calling the FileChannel.getLock() method. See here for an instance of locking a file inward Java earlier writing into it.

8) Make certain you lot know the correct means to unopen the current inward Java because calling the unopen itself tin throw IOException. See my postal service nearly how to properly unopen input together with output current inward Java to acquire more.



9) The java.io together with java.nio parcel provides several classes to write dissimilar kinds of information on the dissimilar situation.  For example, you lot tin use
  •  PrintWriter to write formatted text;
  •  FileOutputStream to write binary data; 
  •  FileWrite to author text data, 
  •  DataOutputStream to write primitive information types; 
  •  RandomAccessFile to write to a specific position, and 
  •  FileChannel to write faster inward bigger files.


10) Use the JDK vii novel file API equally much equally possible, peculiarly for writing novel code. Spend simply about fourth dimension know together with empathize the novel File API introduced inward JDK 7, at to the lowest degree the java.nio.file.Files class, which allows you lot to create, read, write, copy, move, together with delete files together with directories inward Java.


That's all nearly simply about of the interesting together with useful points to retrieve piece dealing amongst a file inward Java. If you lot know these points hence you lot tin effectively read together with write information from a file, avoiding mutual mistakes made past times many Java programmers, who don't know the JDK's file API better. To live on honest, it's non the most intuitive library together with simply about efforts receive got been made inward JDK vii past times introducing the New File API but still, you lot can't ignore these points if you lot are dealing amongst files inward Java.

Thanks for reading this article hence far. If you lot similar this article together with my tips for reading together with writing files inward Java hence delight part amongst your friends together with colleagues. If you lot receive got whatever questions or feedback hence delight drib a note.