Thursday, December 23, 2010

Linux-Shell Programming

1. Write a program to print details of currently logged in users,
print date and calendar?
          #/bin/bash
          echo "Current login users: "
          who
          echo "Date: `date`"
          echo "Calendar: `cal`"

2. Write a program to define user defined variables 'x' with value
'10' and 'y' '20' and print it on screen?
          #/bin/bash
          a=10
          b=20
          echo "a = $a , b = $b"

3. Write a program to print current shell, present working directory,
and username, using system variable?
          #/bin/bash
          echo "Shell: $SHELL"
          echo "Current Directory: `pwd`"
          echo "User name: `whoami`"

4. Write a program to print the sum of two numbers a=10, b=20?
          #/bin/bash
          a=10
          b=20
          echo "Sum: `expr $a + $b`"

5. Write a program to read two numbers from the keyboard and to print
the sum, product and quotient of the numbers?
          #/bin/bash
          echo "Enter the first number: "
          read a
          echo "Enter the second number: "
          read b
          sum=`expr $a + $b`
          echo "Sum is: $sum"
          pro=`expr $a \* $b`
          echo "Product is: $pro"
          quo=`expr $a / $b`
          echo "Quotient is: $quo"

6. Write a program to obtain and print the status of any one command?
          #/bin/bash
          echo "hi"
          a=$?
          if [ $a -eq 0 ]
          then
          echo "Execution successfully completed"
          else
          echo "Execution failed"
          fi

7. Write a program to check the following condition:
Read a number from the keyboard; if that number is greater than '0'
then print as "Positive", else print as "Negative”?
          #/bin/bash
          echo "Enter a number: "
          read a
          if [ $a -gt 0 ]
          then
          echo "Number is positive"
          else
          echo "Number is negative"
          fi

8. Write a program to implement choices:
                         1. Windows
                         2. Linux
                         Select your choice [1 or 2]
Read the choice from keyboard. If that is '1' the print "Windows", if
that is '2' then print "Linux" else print "You don’t like Windows or
Linux"?
          #/bin/bash
          echo "1. Windows"
          echo "2. Linux"
          echo "    Select [1 or 2]"
          read ch
          if [ $ch -eq 1 ]
          then
          echo "Windows"
          else if [ $ch -eq 2 ]
          then
          echo "Linux"
          else
          echo "You dont like Windows or Linux"
          fi
          fi

9. Write a program to prepare students record consisting of name,
roll no, and marks of three subjects. Take sum of the three marks and
print all details of student with total mark?
          #/bin/bash
          echo "Enter Student Details"
          echo "Name: "
          read name
          echo "Roll No: "
          read roll
          echo "Mark1: "
          read m1
          echo "Mark2: "
          read m2
          echo "Mark3: "
          read m3
          tot=`expr $m1 + $m2 + $m3`
          echo "Student Record"
          echo "Name: $name"
          echo "Roll No: $roll"
          echo "Total marks: $tot"

10. Write a program to print cut 5 to 8 columns from any textile?
          #/bin/bash
          cut -c 5-8 textile

11. Write a simple program using awk?
          #/bin/bash
          awk '{ print $1 }' textile

12. Write a program to search a specific word from a file, first read
word from keyboard then using grep command search that word, and take
status of that command, if status is success the print "Word Found"
else print "Word not Found"?
          #/bin/bash
          echo "Enter a pattern to search"
          read pat
          grep $pat textile
          if [ $? -eq 0 ]
          then
          echo "Word Found"
          else
          echo "Not found"
          fi

Linux-More commands

To show the full path of shell commands found in your path
     which <command name>
          eg: which grep
               //output like: /bin/grep

To locate the program, source code, and manual page for a command
     whereis <command name>
                                 
To search for files anywhere on the file system
     locate <keyword to search>
           //find all files and directories that contain the keyword

To search for files matching certain patterns
     find <directory name> <pattern to search>
           eg: find . -name \*mp3
           //starts searching in the current directory “.” and all
subdirectories, looking for files with “mp3” at the end of their
names


To list currently running process
     ps
 
To list all process in the system
     ps -aux
 
To show who is logged on and what they are doing
     w
     who
 
To view the name of current user
     whoami
 
To view the user details
     finger
 
To view host name
     hostname
 
To set host name
     hostname -a <new host name>
 
To print your user-id and group id's
     id
 
To get report on file system disk space usage
     df
In MB
     df -h
 
To view disk usage in a particular directory
     du
 
To view summary
     du -s
In MB
     du -h
                              
To display CPU processes in a full-screen GUI
     top
     // type “Q” to quit
 
To display amount of free and used memory in the system
     free
 
To display information about your CPU
     cat /proc/cpuinfo
 
To display lots of information about current memory usage
     cat /proc/meminfo
 
To print system information to the screen
     uname -a
 
To print kernel version
     uname -r
 
To display the size of a file
     wc -l
In bytes
     wc -m
In char
     wc -c
In word count
     wc -w
 
To change permission to a file/directory
     chmod [-R] <permissions> <file name/directory name>
           eg: chmod 754 one.txt
           eg: chmod -R 777 /home/songs/
{
     read r=4; write w=2; execute x=1
     Owner      Group     Others
     rwx        r-x       r--
     7          5         4
}
 
To change ownership of a file/directory
     chown [-R] <user name> <file name/directory name>
           eg: chown dhanoop one.txt
           eg: chown -R dhanoop /home/songs/
              
 
To search a file for a particular pattern
     grep [-R] <word to search> <file name/directory name>
           eg: grep science science.txt
                //case-sensitive search
           eg: grep -i science science.txt
                //case-insensitive search
           eg: grep -i ‘spinning top’ science.txt
                //multiword search
           eg: grep -R passwd /etc/
                //search in directory
 
To clear the screen
     clear
 
To display text on screen
     echo “<text to display>”
           eg: echo “Hello”
 
To print a file or program output
     lpr <file name>
           eg: lpr mp3files.txt
     <command> | lpr
           eg: ls -la | lpr
 
To sort a file or program output
     sort
           eg: sort mp3files.txt
 
To switch user
     su <user name>
           //to switch to a particular user account
     su
           //to switch to root account
     su -
           //to switch to root, and log in with root's environment
 
To give an alias name to a command for ease of use
     alias <name>=”<command>”
           eg: alias list=”ls -l”
 
To display last logins of user
     last
 
To display the name of currently working terminal
     tty
 
To block a user
     passwd -l <user name>
 
To unblock a user
     passwd -u <user name>
 
To add a user account
     useradd [options] <username>
 
With specified home directory
     useradd -d <home directory> <user name>
 
With specified shell
     useradd -s <shell> <user name>
 
With specified initial group
     useradd -g <initial group> <user name>
 
With specified expiry date
     useradd -e <YYYY-MM-DD> <user name>
 
To lock/unlock a user account
     usermod [-L or -U] <user name>
 
To delete a user account
     userdel [-r] <user name>
 
To restart the system
     shutdown -r now
          //without delay
 
To turn off the system
     poweroff
 
To reboot the system
     reboot
 
To halt the system
     halt
 
To mount a file system or media
     mount <source> <destination>
          eg: mount /dev/sda1 /mnt
                //mounting first partition of first SATA hard disk
             
          eg: mount /dev/hdb3 /mnt
                //mounting third partition of second hard disk
 
To umount a file system or media
     umount <file system/media>
          eg: umount /mnt
 
To view IP address
     ifconfig
 
To edit IP address temporarily
     ifconfig -a etho <ipaddress>
 
To view partitions and file systems
     fdisk -l
          //view line by line
 
To print selected columns in a file
     cut -c <column range> <file name>
          eg: cut -c 3-5 sem.txt
 
To print particular fields
     awk ‘{ print $<field number> }’ <file name>
          eg: awk ‘{ print $2 }’ sem.txt
                //prints second field
          eg: awk ‘{ print $1 $3 }’ sem.txt
                //prints first and third fields
 
To know the shell
     echo $SHELL
          //the symbol “$” precedes every user or system variable.
          All system variables are BLOCK lettered.
 
To know the home directory
     echo $HOME
 
To print the calendar
     cal
          //prints calendar of current month
     cal <YYYY>
          eg: cal 2010
                //prints calendar of specified year
             
To print the date
     date
 
To temporarily switch to root to execute a single command
     sudo <command>
          eg: sudo ifconfig -a eth0 192.168.1.101
 
To run an executable file
     sh <file name>
          eg: sh new\ file
                //”\ “ denotes white space
     ./<file name>
          eg: ./new\ file
 
To view command history
     history
 
To re execute last command
     !!
 
To execute nth command in history
     !n
          eg: !444
                //executes 44th command in the history
 
To re execute last command that starts with specified character
     !<char>
          eg: !s
              //executes the last command that starts with letter “s”
 
To repeat the last command changing old character to new character
     ^old^new
          eg: ^l^m
                //let “wc -l” be the last command
                     now “wc -m” will be executed

Signals to a process
To list all signals
     kill -l
To kill a process
     kill <process id>                                   
To terminate a process
     kill -9 <process id>
To normally exit a process
     kill -15 <process id>

To login remotely to a system
     ssh [<user name>@]<ip address>
          eg: ssh dhanoopbhaskar@192.168.1.101
 
To execute a command on remote system through remote login
     ssh [<user name>@]<ip address> <command>
          eg: ssh dhanoopbhaskar@192.168.1.101 df -h
               //executing “df -h” remotely
 
To copy file from a remote system
     scp [-r] <source> <destination>
          eg: scp /home/a.c dhanoopbhaskar@192.168.1.101:/home/

Linux-Working with files

To find the type of a file
     file <file name>
To create a file
     cat > filename.txt
          //type the contents and press Ctrl+D to exit
To display the contents of a text file
     cat <file name>
To view the contents of a file page by page
     more <file name>
          //traversal only in forward direction
     less <file name>
          //traversal in both directions
To display first few lines of a file
     head <file name>
     head -5 <file name>
          //first 5 lines
To display last few lines of a file
     tail <file name>
     tail -5 <file name>
          //last 5 lines
To display the last few lines of a text file, and then output
appended data as the file grows (very useful for following log
files!)
     tail -f /var/log/messages
To copy a file from one location to another
     cp [-r] <source file/directory> <destination>
          eg: cp mp3files.txt /tmp
To move a file to a new location
     mv <source> <destination>
          eg: mv mp3files.txt /tmp
To delete a file
     rm [-r] <filename/directory name>
          eg: rm /tmp/mp3files.txt

Linux-Working with directories

To print working directory
     pwd

To change directory
To return to home directory
     cd
To change into specified directory name
     cd <directory name>
                                 
To change to home or other path relative to home.
“~” is an alias for your home directory
     cd ~
To move up one directory
     cd ..
To return to previous directory
     cd -

To list all files in the current directory
To list all files in the current directory, in column format
     ls
To list the files in the specified directory
     ls <directory name>
To list files in “long” format, 1 file per line with additional
information
     ls -l
To list all files, including “hidden” files
     ls -a
To show the directory's detailed information
     ls -ld <directory name>
To list all files whose names begin with the letter “d” in the
/usr/bin directory
     ls /usr/bin/d*
To list files based on their size
     ls -sh

To create a directory
     mkdir <directory name>
          eg: mkdir dhan
     mkdir -p <directory path>
          eg: mkdir -p /home/sng/dhan

To create directories in multiple paths
     mkdir -p parent/{child1,child2,child3}
          eg: mkdir -p work/{in,out,pending}/{a,b,c}

To delete a directory
     rmdir <directory name>
          eg: rmdir /tmp/myfiles/

Linux-help commands

To get help on commands
     help <command name>
          eg: help cat
     <command name> --help
          eg: grep --help
     <command name> -h
          eg: chmod -h
     whatis <command name>
          eg: whatis grep

To get “man” pages
     man <command name>
          eg: man ls
To search for a particular word within a man page
     type “/word”.
To quit from a man page, just
     type the “Q” key.
If you don’t remember the actual command
     man -k <keyword to search>
          eg: man -k permission
          You will find a line in the output that looks something
like: chmod (1) - change file access permissions

To get “info” pages
     info <command name>

Linux-Directory Layout


Directory
Description

The nameless base of the file system. All other directories, files, drives, and devices are attached to this root. Commonly (but incorrectly) referred to as the “slash” or “/” directory. The “/” is just a directory separator, not a directory itself.
/bin
Essential command binaries (programs) are stored here (bash, ls, mount, tar, etc.)
/boot
Static files of the boot loader.
/dev
Device files. In Linux, hardware devices are accessed just like other files, and they are kept under this directory.
/etc
Host-specific system configuration files.
/home
Location of users' personal home directories (e.g./home/dhanoop).
/lib
Essential shared libraries and kernel modules.
/proc
Process information pseudo-file system. An interface to kernel data structures.
/root
The root (super-user) home directory.
/sbin
Essential system binaries (fdisk, fsck, init, etc).
/tmp
Temporary files. All users have permission to place temporary files here.
/usr
The base directory for most shareable, read-only data (programs, libraries, documentation, and much more).
/usr/bin
Most user programs are kept here (cc, find, du, etc.).
/usr/include
Header files for compiling C programs.
/usr/lib
Libraries for most binary programs.
/usr/local
Locally” installed files. This directory only really matters in environments where files are stored on the network. Locally-installed files go in /usr/local/bin, /usr/local/lib, etc.). Also often used for software packages installed from source, or software not officially shipped with the distribution.
/usr/sbin
Non-vital system binaries (lpd, useradd, etc.)
/usr/share
Architecture-independent data (icons, backgrounds, documentation, terminfo, man pages, etc.).
/usr/src
Program source code. E.g. The Linux Kernel, source RPMs, etc.
/usr/X11R6
The X Window System.
/var
Variable data: mail and printer spools, log files, lock files, etc.

Linux-basics


Character
Description
\
Escape character. If you want to reference a special character, you must “escape” it with a backslash first.
Example: touch /tmp/filename\*
/
Directory separator, used to separate a string of directory names.
Example: /usr/src/linux
.
Current directory. Can also “hide” files when it is the first character in a filename.
..
Parent directory
~
User's home directory
*
Represents 0 or more characters in a filename, or by itself, all files in a directory.
Example: pic*2002 can represent the files pic2002, picJanuary2002,picFeb292002, etc.
?
Represents a single character in a filename.
Example: hello?.txt can represent hello1.txt, helloz.txt, but not hello22.txt
[ ]
Can be used to represent a range of values, e.g. [0-9], [A-Z], etc.
Example: hello[0-2].txt represents the names hello0.txt,hello1.txt, and hello2.txt
|
Pipe”. Redirect the output of one command into another command.
Example: ls | more
>
Redirect output of a command into a new file. If the file already exists, over-write it.
Example: ls > myfiles.txt
>>
Redirect the output of a command onto the end of an existing file.
Example: echo .Mary 555-1234. >> phonenumbers.txt
<
Redirect a file as input to a program.
Example: more < phonenumbers.txt
;
Command separator. Allows you to execute multiple commands on a single line.
Example: cd /var/log ; less messages
&&
Command separator as above, but only runs the second command if the first one
finished without errors.
Example: cd /var/logs && less messages
&
Execute a command in the background, and immediately get your shell back.
Example: find / -name core > /tmp/corefiles.txt &

Java-Multithreading



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

           /*Method No.1
Counter ctr = new Counter();
           ctr.start();*/
          
           /*Method No.2*/
           Thread thread = new Thread(new Counter());
           thread.start();
     }
}

/*Method No.1
class Counter extends Thread {
     public void run() {
           int ctr = 1;

           while (ctr <= 10) {
                System.out.println(ctr++);
                try {
                     sleep(1000);
                } catch (InterruptedException ex) {
                }
           }
     }
}*/

/*Method No.2*/
class Counter implements Runnable {
     public void run() {
           int ctr = 1;

           while (ctr <= 10) {
                System.out.println(ctr++);
                try {
                     Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
           }
     }
}

Java-TCP socket programming


import java.net.*;
import java.io.*;

public class Client1 {
  public static void main(String[] args) throws Exception {
    String hostAddr = "127.0.0.1"; // Loopback Address
    int hostPort = 8000;

    System.out.println("Client requesting for connection...");
    Socket clientSideSocket = new Socket(hostAddr, hostPort);
    System.out.println("Connection established.");

    PrintWriter serverWriter = new PrintWriter(
                clientSideSocket.getOutputStream(), true);

    System.out.println("Key in a message for the server:");
    serverWriter.println(new BufferedReader(
                new InputStreamReader(System.in)).readLine());
    System.out.println("Message sent to server.");
  }
}
---------------------- ----------------------
import java.net.*;
import java.io.*;

public class Server1 {
  public static void main(String[] args) throws Exception {
    int port = 8000;
    ServerSocket serverSocket = new ServerSocket(port);

    System.out.println("Server Started. Waiting for connection...");
    Socket serverSideClientSocket = serverSocket.accept();
    System.out.println("Client connection request received.");
    System.out.println("Sockets bound and ready for communication.");

    BufferedReader clientReader = new BufferedReader(new InputStreamReader(
                serverSideClientSocket.getInputStream()));
    
    System.out.println("Waiting for message from client...");
    String messageFromClient = clientReader.readLine();
    System.out.println("Client says: " + messageFromClient);
  }
}

--------------------------------------------------------------
import java.net.*;
import java.io.*;

public class Client2 {
  public static void main(String args[]) {
    try {
      Socket clientSideSocket = new Socket("localhost", 8000);
      BufferedReader serverReader = new BufferedReader(
                new InputStreamReader(clientSideSocket.getInputStream()));
      PrintWriter serverWriter = new PrintWriter(
                     clientSideSocket.getOutputStream(), true);
                BufferedReader keyboardReader = new BufferedReader(
                     new InputStreamReader(System.in));
     
                double radius = 0;
      while (true) {
        System.out.print("Please enter the Radius of a Circle...");
        radius = Double.parseDouble(keyboardReader.readLine());
        serverWriter.println(radius);
                     if (radius != 0) {
                           double area = Double.parseDouble(
serverReader.readLine());
                           System.out.println("Area received from the Server: " +
                                area);
                     } else {
                           break;
                     }
      }
    } catch(IOException e) {
    }
  }
}

---------------------- ----------------------
import java.io.*;
import java.net.*;

public class Server2 {
  public static void main(String[] args) {
    try {
      ServerSocket serverSocket = new ServerSocket(8000);
      Socket serverSideClientSocket = serverSocket.accept();

      BufferedReader clientReader = new BufferedReader(
                     new InputStreamReader(
                     serverSideClientSocket.getInputStream()));
      PrintWriter clientWriter = new PrintWriter(
                     serverSideClientSocket.getOutputStream(), true);
      while (true) {
        double radius = Double.parseDouble(clientReader.readLine());
                     if (radius != 0) {
                           System.out.println("Radius Received from Client: " +
                                radius);
                           double area = radius * radius * Math.PI;
                           clientWriter.println(area);
                     } else {
                           break;
                     }
      }
    } catch(IOException e) {
      //System.out.println(e);
    }
  }
}

Wednesday, December 22, 2010

Java-Serialization and De-serialization

import java.io.*;

public class Student implements Serializable {
private int rollNo;
private String name;
transient int age;
public Student(int rollNo, String name, int age) {
this.rollNo = rollNo;
this.name = name;
this.age = age;
}
public int getRollNo() {
return rollNo;
}
public String getName() {
return name;
}
}
-----------------------------------------------------------
import java.io.*;

public class TestObjectInputStream {
public static void main(String s[]) throws IOException,
ClassNotFoundException {
/*FileInputStream fileInStream =
new FileInputStream("Student.ser");
ObjectInputStream objInStream =
new ObjectInputStream(fileInStream);*/

ObjectInputStream objInStream =
new ObjectInputStream(
new FileInputStream("Student.ser"));

System.out.println("Deserializing object s1...");
Student s1 = (Student) objInStream.readObject();
System.out.println("Object s1 deserialized.");

System.out.println("Roll No.: " + s1.getRollNo());
System.out.println("Name : " + s1.getName());
System.out.println("Age : " + s1.age);

objInStream.close();
}
}
--------------------------------------------------------------------
import java.io.*;

public class TestObjectOutputStream {
public static void main(String s[]) throws IOException {
/*FileOutputStream fileOutStream =
new FileOutputStream("Student.ser");
ObjectOutputStream objOutStream =
new ObjectOutputStream(fileOutStream);*/

ObjectOutputStream objOutStream =
new ObjectOutputStream(
new FileOutputStream("Student.ser"));

Student s1 = new Student(12, "Arvind", 14);

System.out.println("Serializing object s1...");
objOutStream.writeObject(s1);
System.out.println("Object s1 serialized.");
objOutStream.close();
}
}

Java-Renaming a file

import java.io.*;

class TestFile {
public static void main(String[] args) throws Exception {
File file = new File(args[0]);
System.out.println(file.getAbsolutePath());

File oldFile = new File("a.txt");
File newFile = new File("b.txt");
oldFile.renameTo(newFile);

if (new File("a.txt").renameTo(new File("b.txt"))) {
} else {
}

}
}

Java-Moving a file

import java.io.*;

public class MoveFile {
public static void main(String args[]) throws IOException {
switch (args.length) {
case 0:
System.out.println("Error in usage:");
System.out.println("Usage: java MoveFile ");
break;
case 1:
System.out.println("Specify the destination file.\n");
System.out.println("\tUsage: java MoveFile ");
break;
case 2:
File source_file = new File(args[0]);
File dest_file = new File(args[1]);

/********************************************************************
* If the file does not exist, show an error message *
* and stop the program. *
********************************************************************/
if (! source_file.exists()) {
System.out.println(args[0] + " Not Found !!!");
System.exit(0);
}

/********************************************************************
* If the file exists, ask if the file is to be overwritten. *
* (i) If the response is "Y" or "y", then overwrite it by *
* invoking the move method. *
* (ii)If the response is "N" or "n", then cancel move operation. *
********************************************************************/
if (dest_file.exists()) {
System.out.print(args[1] + " file already exists. Overwrite? (y/n): ");
int response = System.in.read();
if (response == 'Y' || response == 'y') { // if you do not want to overwrite the file.
moveFile(source_file, dest_file); // user-defined function
} else {
System.out.println("File move operation aborted !!!");
System.exit(0);
}
} else {
moveFile(source_file, dest_file);
}
}
}
public static void moveFile(File source_file, File dest_file) throws IOException {
System.out.print("Move file? (y/n): ");
System.in.skip(System.in.available());//Emptying the Keyboard Buffer.
int response = System.in.read();
if (response == 'Y' || response == 'y') { // if you want to move the file.
/**********************************************************************
* Creating streams for reading and writing source/destination files. *
**********************************************************************/
String source_file_str = source_file.getAbsolutePath();
String dest_file_str = dest_file.getAbsolutePath();

String source_file_dir =
source_file_str.substring(0,
source_file_str.lastIndexOf('\\'));//truncating the filename
String dest_file_dir =
dest_file_str.substring(0,
dest_file_str.lastIndexOf('\\'));

System.out.println("Source File Abs Path: " +
source_file_str);
System.out.println("Source Dir: " + source_file_dir);
System.out.println("Dest File Abs Path: " + dest_file_str);
System.out.println("Dest Dir: " + dest_file_dir);

if (source_file_dir.equals(dest_file_dir)) {
System.out.println("Renaming file " +
source_file.getName() + " to " +
dest_file.getName() + " !!!");
source_file.renameTo(new File(dest_file.getName()));
} else {
FileInputStream input_file = new FileInputStream(
source_file);
FileOutputStream output_file = new FileOutputStream(
dest_file);
/**********************************************************************
* (i) Finding the size of the source file using available(). *
* (ii) Creating a byte array, the no. of elements of which is equal *
* to the size of source file. *
* (iii)Read data from the source file into the byte array. *
* (iv) Write the byte array to the destination file. *
**********************************************************************/
System.out.println("Moving file " +
source_file.getName() + " to " +
dest_file.getName() + " !!!");
int file_size = input_file.available();
byte input_file_data[] = new byte[file_size];
input_file.read(input_file_data);
output_file.write(input_file_data);

/**********************************************************************
* Close the input/output streams. *
**********************************************************************/
input_file.close();
output_file.close();

source_file.delete();
}

/**********************************************************************
* Delete the source file and return a successful process message. *
**********************************************************************/

System.out.println("File " + source_file.getName() +
" successfully moved to " + dest_file.getName() + " !!!");
} else {// if you do not want to move the file.
System.out.println("File move operation aborted !!!");
System.exit(0);
}
}
}

Java-Copying a file

import java.io.*;

public class CopyFile {
public static void main(String[] args) throws IOException {
switch (args.length) {
case 0:
System.out.println("Error in usage:");
System.out.println(
" Usage: java CopyFile ");
break;
case 1:
System.out.println(
"Specify the destination file.");
System.out.println(
" Usage: java CopyFile ");
break;
case 2:
File sourceFile = new File(args[0]);
File destFile = new File(args[1]);

if (! sourceFile.exists()) {
System.out.println(args[0] + " not found !!!");
System.exit(0); // stopping application
}

if (destFile.exists()) {
System.out.print(args[1] +
" file already exists. Overwrite? (y/n): ");
int response = System.in.read();
if (response == 'N' || response == 'n') {
// if you do not want to overwrite the file.
System.out.print("Copy operation aborted.");
System.exit(0); // stopping application
}
}

System.out.println("Copying file...\n" +
args[0] + " to " + args[1]);

FileInputStream inputFile =
new FileInputStream(sourceFile);
FileOutputStream outputFile =
new FileOutputStream(destFile);

//boolean arg is for "append"
/*FileOutputStream outputFile =
new FileOutputStream(destFile, true);

FileOutputStream outputFile =
new FileOutputStream(args[1]);

FileOutputStream outputFile =
new FileOutputStream(args[1], true);*/

byte[] inputFileData =
new byte[inputFile.available()];
inputFile.read(inputFileData);
outputFile.write(inputFileData);

inputFile.close();
outputFile.close();

System.out.println("File successfully copied !");

}
}
}

/*File oldFile = new File("abc.txt");
File newFile = new File("xyz.txt");
oldFile.renameTo(newFile);

new File("abc.txt").renameTo(new File("xyz.txt"));*/

Java-Writing to a file

import java.io.*;

public class WriteFile {
public static void main(String args[]) throws IOException {
if (args.length != 0) {
File file = new File(args[0]);

if (file.exists()) {
System.out.print("This file already exists. Overwrite? (y/n): ");
int response = System.in.read();
if(response == 'N'||response =='n') {
// if you do not want to overwrite the file.
System.exit(0); // stop program
}
} else {
System.out.print("Creating new file: " + args[0] + "...");
}

System.out.println();
System.out.println(
"[Press \'~\' as the first char on a new line to terminate the file.]");
System.out.println("Enter data for file: " + args[0]);
System.out.println(
"--------------------------------------------------------------------------------");

FileOutputStream output_file = new FileOutputStream(file); // output file.
boolean continue_write = true;
byte[] data; // byte array to which the data is read into.
while (continue_write) {
// continue reading lines till the user types '~' and ENTER.
data = new BufferedReader(
new InputStreamReader(System.in)).readLine().getBytes();
if (data.length == 1 && ((char)data[0]) == '~') {// if end-of-file
continue_write = false;
} else {// if not end-of-file
output_file.write(data);
output_file.write('\n');
}
}
System.out.println(
"--------------------------------------------------------------------------------");
output_file.close();
} else {//end of while
System.out.println("Usage: java WriteFile ");
}
}
}



/*public class WriteFile
{
public static void main(String args[]) throws IOException
{
if(args.length!=0)
{
File file=new File(args[0]);

if(file.exists())
{
System.out.print("This file already exists. Overwrite? (y/n): ");
int response=System.in.read();
if(response=='N'||response=='n')
// if you do not want to overwrite the file.
{
System.exit(0); // stop program
}
}
else
System.out.print("Creating new file: " + args[0] + "...");


System.out.println();
System.out.println(
"[Press \'~\' as the first char on a new line to terminate the file.]");
System.out.println("Enter data for file: " + args[0]);
System.out.println(
"--------------------------------------------------------------------------------");

PrintWriter output_file=new PrintWriter(
new FileOutputStream(file), true); // output file.
boolean continue_write=true;
String line;
while(continue_write)
// continue reading lines till the user types '~' and ENTER.
{
line=new BufferedReader(new InputStreamReader(System.in)).readLine();
if(line.length()==1 && line.equals("~")) // if end-of-file
continue_write=false;
else // if not end-of-file
output_file.println(line);
}
System.out.println(
“--------------------------------------------------------------------------------“);
output_file.close();
}
else
System.out.println(“Usage: java WriteFile ”);
}
}*/

Java-Reading a file


import java.io.*;

public class ShowFile {
  public static void main(String args[]) throws IOException {
    if (args.length != 0) {
      File file = new File(args[0]);
      if (file.exists() && file.isFile()) {
        FileInputStream input_file =
                           new FileInputStream(file);
        /*FileInputStream input_file =
                     new FileInputStream(args[0]);*/
        int file_size = input_file.available();
        byte[] data = new byte[file_size];
        input_file.read(data);
        System.out.println(new String(data));
        input_file.close();
      } else {
        System.out.println("\"" + args[0] +
                           "\" not found !!!");
                }
    } else {
      System.out.println("Error in usage:");
      System.out.println(
                     "  Usage - java ShowFile ");
           }
  }
}

Contact Form

Name

Email *

Message *

The Insane Techie - Android App

Launched an android app for the blog on 07th June 2016. Get it from google play store... Tips for using the app Use in landscape mo...