1).ANSWER:
GIVEN BELOW:
Java Command-Line Arguments
The command-line arguments in Java allow us to pass arguments during the execution of the program. The arguments are passed through the command line.
Example of Command-Line Arguments:
class Command {
public static void main(String[] args) {
System.out.println("Command-Line arguments are");
// loop through all arguments
for(String str: args) {
System.out.println(str);
}
}
}
To compile the code---à javac Command.java
To run the code-----à java Command
Now to pass some arguments while running the program, we can pass the arguments after the class name.
Example :
java Main be your own hero
Here be your own and hero are arguments passed to the program through the command line. Now, we will get the following output.
Output
Command-Line arguments are
Be
Your
Own
Hero
In the above program, the main() method includes an array of strings named args as its parameter.
public static void main(String[] args) {...}
The String array stores all the arguments passed through the command line.
Arguments are always stored as strings and always separated by white-space.
Passing Numeric Command-Line Arguments
The main() method of every Java program only accepts string arguments. Hence it is not possible to pass numeric arguments through the command line.
However, we can later convert string arguments into numeric values.
Example: Numeric Command-Line Arguments
class Main {
public static void main(String[] args) {
for(String str: args) {
// convert into integer type
int argument = Integer.parseInt(str);
System.out.println("Argument in integer form: " + argument);
}
}
}
OUTPUT
To compile the code
javac Main.java
To run the code by passing the numeric arguments
java Main 47 31
Here 47 and 31 are command-line arguments. Now, we will get the following output.
Arguments in integer form
47
31
In the above example, notice the line
int argument = Intege.parseInt(str);
Here, the parseInt() method of the Integer class converts the string argument into an integer.
Similarly, we can use the parseDouble() and parseFloat() method to convert the string into double and float respectively.
If the arguments cannot be converted into the specified numeric value then an exception named NumberFormatException occurs.
PASSING FILE PATH AS AN ARGUMENT
Consider an example:
public static void main(String[] args) {
fileReader fr = new fileReader();
getList lists = new getList();
File CP_file = new File("C:/Users/XYZ/workspace/Customer_Product_info.txt");
int count = fr.fileSizeInLines(CP_file);
System.out.println("Total number of lines in the file are: "+count);
List<String> lines = fr.strReader(CP_file);
}
}
fileReader.java file has the following function:
public List<String> strReader (File in)
{
List<String> totLines = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader(in));
String line;
while ((line = br.readLine()) != null)
{
totLines.add(line);
}
br.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//String result = null;
return totLines;
}
File path to be passed as a Command line Argument:
public static void main(String[] args) {
String path = args[0];
// ...
File CP_file = new File(path);
// ...
}
_______________________
File CP_file = new File(arg[0]); //Assuming that the path is the first argument
_______________________
Reading arguments from your main(String[]) method
Now this one is simple: as others have pointed out, the String with your path should now be in args[0]:
public static void main(String[] args) {
fileReader fr = new fileReader();
getList lists = new getList();
if (args[0] == null || args[0].trim().isEmpty()) {
System.out.println("You need to specify a path!");
return;
} else {
File CP_file = new File(args[0]);
int count = fr.fileSizeInLines(CP_file);
System.out.println("Total number of lines in the file are: "+count);
List<String> lines = fr.strReader(CP_file);
}
}
_____________________________
When reading and writing binary files:
it's almost always a good idea to use buffering (default buffer
size is 8K)
it's often possible to use references to abstract base classes,
instead of references to specific concrete classes
there's always a need to pay attention to exceptions (in
particular, IOException and FileNotFoundException)
Small Files Example:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public final class SmallBinaryFiles {
public static void main(String... args) throws IOException {
SmallBinaryFiles binary = new SmallBinaryFiles();
byte[] bytes = binary.readSmallBinaryFile(FILE_NAME);
log("Small - size of file read in:" + bytes.length);
binary.writeSmallBinaryFile(bytes, OUTPUT_FILE_NAME);
}
final static String FILE_NAME = "C:\\Temp\\cottage.jpg";
final static String OUTPUT_FILE_NAME = "C:\\Temp\\cottage_output.jpg";
byte[] readSmallBinaryFile(String fileName) throws IOException {
Path path = Paths.get(fileName);
return Files.readAllBytes(path);
}
void writeSmallBinaryFile(byte[] bytes, String fileName) throws IOException {
Path path = Paths.get(fileName);
Files.write(path, bytes); //creates, overwrites
}
private static void log(Object msg){
System.out.println(String.valueOf(msg));
}
}
This example reads and writes binary data, moving it from disk to memory, and then back again.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public final class BytesStreamsAndFiles {
private static final String INPUT_FILE_NAME = "C:\\TEMP\\cottage.jpg";
private static final String OUTPUT_FILE_NAME = "C:\\TEMP\\cottage_copy.jpg";
public static void main(String... args) {
BytesStreamsAndFiles test = new BytesStreamsAndFiles();
byte[] fileContents = test.read(INPUT_FILE_NAME);
test.write(fileContents, OUTPUT_FILE_NAME);
}
byte[] read(String inputFileName){
log("Reading in binary file named : " + inputFileName);
File file = new File(inputFileName);
log("File size: " + file.length());
byte[] result = new byte[(int)file.length()];
try {
InputStream input = null;
try {
int totalBytesRead = 0;
input = new BufferedInputStream(new FileInputStream(file));
while(totalBytesRead < result.length){
int bytesRemaining = result.length - totalBytesRead;
int bytesRead = input.read(result, totalBytesRead, bytesRemaining);
if (bytesRead > 0){
totalBytesRead = totalBytesRead + bytesRead;
}
}
log("Num bytes read: " + totalBytesRead);
}
finally {
log("Closing input stream.");
input.close();
}
}
catch (FileNotFoundException ex) {
log("File not found.");
}
catch (IOException ex) {
log(ex);
}
return result;
}
void write(byte[] input, String outputFileName){
log("Writing binary file...");
try {
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(outputFileName));
output.write(input);
}
finally {
output.close();
}
}
catch(FileNotFoundException ex){
log("File not found.");
}
catch(IOException ex){
log(ex);
}
}
byte[] readAlternateImpl(String inputFileName){
log("Reading in binary file named : " + inputFileName);
File file = new File(inputFileName);
log("File size: " + file.length());
byte[] result = null;
try {
InputStream input = new BufferedInputStream(new FileInputStream(file));
result = readAndClose(input);
}
catch (FileNotFoundException ex){
log(ex);
}
return result;
}
byte[] readAndClose(InputStream input){
byte[] bucket = new byte[32*1024];
ByteArrayOutputStream result = null;
try {
try {
result = new ByteArrayOutputStream(bucket.length);
int bytesRead = 0;
while(bytesRead != -1){
bytesRead = input.read(bucket);
if(bytesRead > 0){
result.write(bucket, 0, bytesRead);
}
}
}
finally {
input.close();
}
}
catch (IOException ex){
log(ex);
}
return result.toByteArray();
}
private static void log(Object thing){
System.out.println(String.valueOf(thing));
}
}
Java.io.FileInputStream Class in Java
FileInputStream is useful to read data from a file in the form of sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
Constructor and Description
FileInputStream(File file) :Creates an input file stream to read
from the specified File object.
FileInputStream(FileDescriptor fdobj) :Creates an input file stream
to read from the specified file descriptor.
FileInputStream(String name) :Creates an input file stream to read
from a file with the specified name.
Important Methods:
int read() : Reads a byte of data from this input stream.
Syntax: public int read()
throws IOException
Returns: the next byte of data, or -1 if the end of the file is
reached.
Throws:
IOException
int read(byte[] b) :Reads up to b.length bytes of data from this
input stream into an array of bytes.
Syntax:public int read(byte[] b)
throws IOException
Parameters:
b - the buffer into which the data is read.
Returns: the total number of bytes read into the buffer, or
-1.
Throws:
IOException
int read(byte[] b, int off, int len) : Reads up to len bytes of
data from this input stream into an array of bytes.
Syntax:public int read(byte[] b,
int off,
int len)
throws IOException
Parameters:
b - the buffer into which the data is read.
off - the start offset in the destination array b
len - the maximum number of bytes read.
Returns: the total number of bytes read into the buffer, or
-1
Throws:
NullPointerException
IndexOutOfBoundsException
long skip(long n) : Skips over and discards n bytes of data from
the input stream.
Syntax:public long skip(long n)
throws IOException
Parameters:
n - the number of bytes to be skipped.
Returns: the actual number of bytes skipped.
Throws:
IOException
int available() : Returns an estimate of the number of remaining
bytes that can be read (or skipped over) from this input stream
.
Syntax:public int available()
throws IOException
Returns: an estimate of the number of remaining bytes that can be
read
Throws:
IOException
· void close() : Closes this file input stream and releases any system resources associated with the stream.
· Syntax:public void close()
· throws IOException
· Specified by:
· close in interface AutoCloseable
· Overrides:
· close in class InputStream
· Throws:
IOException
· FileDescriptor getFD() :Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.
· Syntax :public final FileDescriptor getFD()
§ throws IOException
· Returns: the file descriptor object associated with this stream.
Throws: IOException
· FileChannel getChannel() :Returns the unique FileChannel object associated with this file input stream.
· Syntax :public FileChannel getChannel()
Returns: the file channel associated with this file input stream
· void finalize() :Ensures that the close method of this file input stream is called when there are no more references to it.
· Syntax :protected void finalize()
o throws IOException
· Overrides: finalize in class Object
Throws: IOException
Steps to read data from a file using FileInputStream
First , attach file to a FileInputStream as shown here:
FileInputStream fileInputStream =new
FileInputStream(“file.txt”);
This will enable us to read data from the file. Then , to read
data from the file, we should read data from the FileInputStream
as;
ch=fileInputStream.read();
When there is no more data available to read further , the read() method returns -1;
Then we should attach the monitor to output stream. For
displaying the data, we can use System.out.print.
System.out.print(ch);
Example : //Java program demonstrating FileInputStream
import java.io.*;
class ReadFile
{
public static void main(String args[]) throws IOException
{
FileInputStream fin= new FileInputStream("file1.txt");
System.out.println(fin.getChannel());
System.out.println(fin.getFD());
System.out.println("Number of remaining bytes:"+fin.available());
fin.skip(4);
System.out.println("FileContents :");
int ch;
while((ch=fin.read())!=-1)
System.out.print((char)ch);
fin.close();
}
}
Output:
sun.nio.ch.FileChannelImpl@1540e19d
java.io.FileDescriptor@677327b6
Number of remaining bytes:45
FileContents :
is my first line
This is my second line
Get Answers For Free
Most questions answered within 1 hours.