Sunday, April 2, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Java

How to Automate Basic File Operations Using Java

learningcode_x1mckf by learningcode_x1mckf
September 28, 2022
in Java
0
How to Automate Basic File Operations Using Java
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


Many purposes must work with information, whether or not they’re writing, transferring, or deleting them. Discover ways to do all this, and extra, utilizing Java.

Drawer with files inside


There are numerous repetitive duties that you could be want to finish occasionally. One instance is that if you must recurrently make modifications to information in your native pc. These actions can embrace copying, transferring, deleting, or archiving information.


As a substitute of finishing these repetitive duties manually, you possibly can automate them utilizing a program. You are able to do this with a single script file, utilizing one of many many programming languages accessible, similar to Java.


The right way to Set Up the Java Software

First, guarantee that you’ve got Oracle’s Java SE Development Kit put in. Then create a easy Java console software:

  1. Create a file wherever in your pc referred to as SimpleScript.java.
  2. Open the file in a textual content editor or IDE.
  3. On the prime of the file, import the IOException Class. It will let you deal with file or IO-related exceptions when making an attempt to do sure features, like copying a file.
    import java.io.IOException;
  4. Under, add the main Java class and the predominant methodology. The primary methodology will run once you begin the applying. For now, simply print a message to make sure this system runs appropriately. After this, you possibly can substitute the contents of the principle perform with any of the next examples to check them.
    class SimpleScript     
    public static void predominant(String args[]) throws IOException
    System.out.println("Easy Console App");

  5. To run the script, begin by utilizing a command line to navigate to the situation of your java file. For instance, when you’ve got saved your file on the Desktop, the command can be:
    cd Desktop
  6. Save the file, and use the javac command to compile it. Each time you make modifications to the file, you’ll must re-compile it with javac.
    javac SimpleScript.java
  7. Run the applying:
    java SimpleScript
    Command Line open with commands to run the Java application

The right way to Entry Native Recordsdata in Your Pc

You need to use the File class to programmatically entry information in a listing.

  1. Create a brand new folder, referred to as NewDirectory, in the identical listing as your java file. Create some information inside it—they are often empty textual content information if you’d like.
  2. On the prime of your Java software, import the File class. It will let you entry sure strategies and different performance associated to OS information and directories.
    import java.io.File;
  3. Create a brand new File object utilizing the relative path to your new folder.
    File listing = new File("NewDirectory");
  4. Use the listFiles() perform to entry an inventory of all of the information inside that listing.
    File[] listOfFiles = listing.listFiles();

    for (File file : listOfFiles)
    System.out.println(file);

  5. Re-compile and run this system utilizing the javac and java instructions.
    The list of files in a folder is printed in the command line

The right way to Copy Recordsdata to One other Location

There are a number of methods you possibly can copy information. A typical technique to copy information (particularly earlier than Java 7 and the java.nio.file package deal), is to make use of the FileInputStream or FileOutputStream lessons.

  • The FileInputStream class permits you to open an enter stream to learn bytes from a file.
  • The FileOutputStream class permits you to open an output stream to jot down bytes to a file.

When copying information, the thought is to open an enter and output stream. Utilizing these streams, you’ll learn the bytes of the file on the supply location, after which write these bytes to the brand new location.

This instance will use a more recent implementation to repeat information, by utilizing the copy() perform from the Recordsdata class of the java.nio.file package deal. To make use of the java.nio.file package deal, you will need to have Java 7 or greater put in.

  1. On the prime of the file, import the File and Path lessons from the java.nio.file package deal.
    import java.nio.file.Recordsdata;
    import java.nio.file.Paths;
  2. Add a brand new file referred to as FileToCopy.txt in the identical listing as your java file. In the principle() perform, declare the relative path to that file.
    String copySource = "FileToCopy.txt"; 
  3. Create a brand new Folder, referred to as NewFolder, to repeat the file to. Add the relative path to the vacation spot in the principle() perform.
    String copyDestination = "NewFolder/FileToCopy.txt";
  4. Use the copy() methodology to repeat the file from its supply to the vacation spot.
    attempt 
    Recordsdata.copy(Paths.get(copySource), Paths.get(copyDestination));
    catch(Exception e)
    System.out.println("Couldn't copy the specs file in: " + copyDestination
    + " . Verify if the folder or file already exists.");
  5. Re-compile and run this system utilizing the javac and java instructions.
  6. Open the New Folder to substantiate that this system has copied your file.
    File Manager open to view the file that was copied

The right way to Transfer Recordsdata or Folders

You may transfer information or folders utilizing the transfer() perform within the Recordsdata class, which can be a part of the java.nio.file package deal.

  1. Create a brand new folder referred to as DirectoryToMove in the identical folder as your Java file.
  2. Create a second folder referred to as NewDirectory in the identical folder. That is the place this system will transfer the unique folder to.
  3. Create File objects for the listing you need to transfer, and the situation you need to transfer it to:
    File moveSource = new File("DirectoryToMove");
    File moveDestination = new File("NewDirectory/DirectoryToMove");
  4. Use the Recordsdata.transfer() methodology to maneuver the file from the supply to the vacation spot:
    attempt 
    Recordsdata.transfer(moveSource.toPath(), moveDestination.toPath());
    System.out.println("Listing moved efficiently.");
    catch (IOException ex)
    ex.printStackTrace();
  5. Re-compile and run this system utilizing the javac and java instructions.
  6. Open the NewDirectory folder to view that the “DirectoryToMove” folder is now inside.

The right way to Delete a File

You need to use the delete() methodology from the File class to delete a selected file.

  1. Create a file referred to as FileToDelete.txt. Save the file in the identical folder as your Java software.
  2. Create a brand new File object for the file you need to delete. Then, use its delete() methodology to delete the file. The delete methodology returns a real or false worth, relying on whether or not the deletion was profitable.
    File fileToDelete = new File("FileToDelete.txt");

    if (fileToDelete.delete())
    System.out.println("File succesfully deleted.");
    else
    System.out.println("Unable to delete the file.");

The right way to Zip Recordsdata

There are numerous methods you possibly can create a zipper archive containing several compressed files. This instance will use the ZipOutputStream and ZipEntry lessons.

  1. Import the required ZipOutputStream, ZipEntry, and FileOutputStream lessons on the prime of the file.
    import java.util.zip.ZipOutputStream;
    import java.util.zip.ZipEntry;
    import java.io.FileOutputStream;
  2. Create the zip file and an inventory of zipEntry objects representing the textual content information you want to zip. This instance will generate new textual content information, however you possibly can modify the script later to incorporate textual content information that exist already.
    File zipFile = new File("ZippedFile.zip");
    ZipEntry[] zipEntries = new ZipEntry[] new ZipEntry("zipFile1.txt"),
    new ZipEntry("zipFile2.txt"), new ZipEntry("zipFile3.txt");
  3. Create the zip output stream to jot down information to the zip file.
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
  4. Add every file to the zip folder, and shut the stream.
    for (ZipEntry zipEntry : zipEntries) 
    out.putNextEntry(zipEntry);

    StringBuilder sb = new StringBuilder();
    sb.append("Content material Inside Textual content File");

    byte[] information = sb.toString().getBytes();
    out.write(information, 0, information.size);
    out.closeEntry();

    out.shut();

  5. Re-compile and run this system utilizing the javac and java instructions. You will note the brand new zip folder seem in your file listing.
    File manager opened to view the contents of a zip folder

You might also like

So why did they decide to call it Java? – InfoWorld

Senior Java Developer – IT-Online

West Java to provide simultaneous polio vaccinations from Apr 3 – ANTARA English

Automating Easy Duties With Java

You need to use a script to finish repetitive file supervisor duties programmatically. These duties embrace accessing, copying, transferring, deleting, and zipping information.

One other approach you possibly can automate repetitive duties is by utilizing system instructions in a script file. On Linux and macOS, such information are generally known as shell scripts, whereas Home windows refers to them as batch scripts.



Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

So why did they decide to call it Java? – InfoWorld

by learningcode_x1mckf
April 1, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

So why did they decide to call it Java?  InfoWorld Source link

Read more

Senior Java Developer – IT-Online

by learningcode_x1mckf
April 1, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Senior Java Developer  IT-On-line Source link

Read more

West Java to provide simultaneous polio vaccinations from Apr 3 – ANTARA English

by learningcode_x1mckf
April 1, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

West Java to provide simultaneous polio vaccinations from Apr 3  ANTARA English Source link

Read more

COBOL programming skills gap thwarts modernization to Java – TechTarget

by learningcode_x1mckf
April 1, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

COBOL programming skills gap thwarts modernization to Java  TechTarget Source link

Read more

User input with a Java JOptionPane example – TheServerSide.com

by learningcode_x1mckf
April 1, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

User input with a Java JOptionPane example  TheServerSide.com Source link

Read more
Next Post
Swift init patterns – The.Swift.Dev.

Swift init patterns - The.Swift.Dev.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

How to Fetch Data in Javascript like a Pro

How to Fetch Data in Javascript like a Pro

October 15, 2022
Picking and playing videos in Swift

Picking and playing videos in Swift

September 28, 2022
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Full Stack Trainings Java-Python-.Net-MERN-MEAN – Greatandhra

February 3, 2023

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • So why did they decide to call it Java? – InfoWorld
  • Senior Java Developer – IT-Online
  • 4 Packages for Working With Date and Time in JavaScript – MUO – MakeUseOf

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?