Monday, January 12, 2015

Get list of all file and All file operations



How to get my machine or local host's Host name in Java

package com.myjava.ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MyLocalHostName
{
 public static void main(String a[])
{
        try
       {
            InetAddress myHost = InetAddress.getLocalHost();
            System.out.println(myHost.getHostName());
        }
         catch (UnknownHostException ex)
         {
            ex.printStackTrace();
        }
    }
}

How to get list of all IPs of a given Host in Java

package com.myjava.ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MyAllIpAddresses
{
public static void main(String a[])
{
           try
           {
            InetAddress[] myHost =                  InetAddress.getAllByName("www.google.com");
            for(InetAddress host:myHost)
            {
                System.out.println(host.getHostAddress());
            }
        }
         catch (UnknownHostException ex)
         {
            ex.printStackTrace();
        }
    }
}

All file operations

package com.java2novice.files;
import java.io.File;
public class MyFileOperations
{
public static void main(String[] a)
{
       try
          {
            File file = new File("fileName");
            System.out.println(file.canRead());
            System.out.println(file.canWrite());
            System.out.println(file.createNewFile());
            System.out.println(file.delete());
            System.out.println(file.exists());
            System.out.println(file.getAbsolutePath());
            System.out.println(file.isDirectory());
            System.out.println(file.isHidden());
            System.out.println(file.list());
        }
         catch(Exception ex){}
    }
}

How to get list of all file names from a folder in java

package com.java2novice.files;
import java.io.File;
public class FileListFromFolder
{
 public static void main(String a[])
{
        File file = new File("C:/MyFolder/");
        String[] fileList = file.list();
        for(String name:fileList)
        {
            System.out.println(name);
        }
    }
}

How to get list of all file objects from a folder in java

package com.java2novice.files;
import java.io.File;
public class FilesListFromFolder
{
public static void main(String a[])
{
        File file = new File("C:/MyFolder/");
        File[] files = file.listFiles();
        for(File f: files)
        {
            System.out.println(f.getName());
        }
    }
}

No comments:

Post a Comment