Saturday, 7 May 2022

Switch case in Java

 Problem statement: Return the capital of a state based on input state


        public String getCapital(String state){

            switch(state)

            {

                case "Tamilnadu":

                            return "Chennai";

                 case "Karnataka":

                            return "Bangalore";

                case "Maharastra":

                            return "Mumbai";

                case "Kerala":

                            return "Trivandrum";

                }

                return null;

          }


Input: Tamilnadu

Output: Chennai


Swap two variables in Java

 


  • With temp variable
                public void swap(int a,int b)
                    {
                        int temp=a;
                        a=b;
                        b=temp;
                    }


  • Without temp variable
                public void swap(int a,int b)
                    {
                        a=a+b;
                        b=a-b;
                        a=a-b;
                    }

Send mail using Java Mail

                 import javax.activation.DataHandler;

        import javax.activation.DataSource;

        import javax.activation.FileDataSource;

        import javax.mail.BodyPart;

        import javax.mail.Message;

        import javax.mail.MessagingException;

        import javax.mail.Multipart;

        import javax.mail.Session;

        import javax.mail.Transport;

        import javax.mail.internet.InternetAddress;

        import javax.mail.internet.MimeBodyPart;

        import javax.mail.internet.MimeMessage;

        import javax.mail.internet.MimeMultipart;


              public static void main(String[] args) {

      String to = "to mail address";

      String from = "from mail address";

      String host = "mail host";

      Properties properties = System.getProperties();

      properties.setProperty("mail.smtp.host", host);

      Session session = Session.getDefaultInstance(properties);


      try {

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.addRecipient(Message.RecipientType.TO, new                                 InternetAddress(to));

        message.setSubject("This is the Subject Line!");

         

        BodyPart messageBodyPart = new MimeBodyPart();

         

        messageBodyPart.setText("This is message body");

         

        Multipart multipart = new MimeMultipart();

         

        multipart.addBodyPart(messageBodyPart);

         

        messageBodyPart = new MimeBodyPart();

        String filename = "filePath";

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

         

        message.setContent(multipart);

         

        Transport.send(message);

        System.out.println("Sent message successfully....");

      } catch (MessagingException mex) {

        mex.printStackTrace();

      }

  }

UnZip files using Java

        import java.io.BufferedOutputStream;

        import java.io.File;

        import java.io.FileInputStream;

        import java.io.FileNotFoundException;

        import java.io.FileOutputStream;

        import java.io.IOException;

        import java.util.zip.GZIPInputStream;

        import java.util.zip.GZIPOutputStream;

        import java.util.zip.ZipEntry;

        import java.util.zip.ZipInputStream;

        import java.util.zip.ZipOutputStream;




       public void unZip(String inputFile, String outputFilePath) {

try {

File destDir = new File(outputFilePath);

byte[] buffer = new byte[1024];

ZipInputStream zis = new ZipInputStream(new FileInputStream(inputFile));

ZipEntry zipEntry = zis.getNextEntry();

while (zipEntry != null) {

File newFile = newFile(destDir, zipEntry);

if (zipEntry.isDirectory()) {

if (!newFile.isDirectory() && !newFile.mkdirs()) {

throw new IOException("Failed to create directory " + newFile);

}

} else {

// fix for Windows-created archives

File parent = newFile.getParentFile();

if (!parent.isDirectory() && !parent.mkdirs()) {

throw new IOException("Failed to create directory " + parent);

}


// write file content

FileOutputStream fos = new FileOutputStream(newFile);

int len;

while ((len = zis.read(buffer)) > 0) {

fos.write(buffer, 0, len);

}

fos.close();

}

zipEntry = zis.getNextEntry();

}

zis.closeEntry();

zis.close();

} catch (Exception e) {

System.out.println(e.getMessage());

}

}


        public static File newFile(File destinationDir, ZipEntry zipEntry) throws             IOException {

File destFile = new File(destinationDir, zipEntry.getName());


String destDirPath = destinationDir.getCanonicalPath();

String destFilePath = destFile.getCanonicalPath();


if (!destFilePath.startsWith(destDirPath + File.separator)) {

throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());

}


return destFile;

}

Gzip files in Java

 

        import java.io.BufferedOutputStream;

        import java.io.File;

        import java.io.FileInputStream;

        import java.io.FileNotFoundException;

        import java.io.FileOutputStream;

        import java.io.IOException;

        import java.util.zip.GZIPInputStream;

        import java.util.zip.GZIPOutputStream;

        import java.util.zip.ZipEntry;

        import java.util.zip.ZipInputStream;

        import java.util.zip.ZipOutputStream;



        public void gZipFile(String inputFile, String outputFile) {

try {

FileInputStream fis = new FileInputStream(inputFile);

FileOutputStream fos = new FileOutputStream(outputFile);

GZIPOutputStream gzipOS = new GZIPOutputStream(fos);

byte[] buffer = new byte[1024];

int len;

while ((len = fis.read(buffer)) != -1) {

gzipOS.write(buffer, 0, len);

}

// close resources

gzipOS.close();

fos.close();

fis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

Zip files using Java

 

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.zip.GZIPInputStream;

import java.util.zip.GZIPOutputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;

import java.util.zip.ZipOutputStream;


public void zipFiles(String[] files, String outputFile) {

FileOutputStream fos = null;

ZipOutputStream zipOut = null;

FileInputStream fis = null;

try {

    fos = new FileOutputStream(outputFile);

    zipOut = new ZipOutputStream(new BufferedOutputStream(fos));

    for (String filePath : files) {

File input = new File(filePath);

fis = new FileInputStream(input);

ZipEntry ze = new ZipEntry(input.getName());

// System.out.println("Zipping the file: " + input.getName());

zipOut.putNextEntry(ze);

byte[] tmp = new byte[4 * 1024];

int size = 0;

while ((size = fis.read(tmp)) != -1) {

zipOut.write(tmp, 0, size);

}

zipOut.flush();

fis.close();

}

zipOut.close();

System.out.println("Done... Zipped the files...");

                catch (FileNotFoundException e) {

                catch (IOException e) {

                finally {

    try {

if (fos != null)

fos.close();

                    catch (Exception ex) {


}

}

}

Read text file

             public String readFile(String filePath) throws IOException {

File file = new File(filePath);


BufferedReader br = new BufferedReader(new FileReader(file));


String st;

                String stringOutput="";

while ((st = br.readLine()) != null) {

stringOutput = stringOutput +st;

}

return stringOutput;

}

Switch case in Java

 Problem statement: Return the capital of a state based on input state          public String getCapital(String state){               switch...