Question

You shall write a Java program that functions similarly to the GNU strings utility. Your program...

You shall write a Java program that functions similarly to the GNU strings utility.
Your program must:
1.Accept any number of command-line arguments, assumed to be file paths.

-If the first command-line argument can be parsed as an integer, this integer shall represent the minimum sequence length.
Otherwise, the minimum sequence length shall be 4 strings.

2.Print, one per line, to standard output, all printable character sequences that are at least as long as the minimum sequence length and are followed by an unprintable character (or the end of a file).

For the purposes of this assignment, a printable character shall consist of one byte that is either a tab character, or any character



Homework Answers

Answer #1

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

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
In Java, Write a small program that gets some numbers as command line arguments and finds...
In Java, Write a small program that gets some numbers as command line arguments and finds the minimum of those numbers. You can assume that the user will provide some command line arguments when running the program (so you don’t have to worry about what to do if the user doesn’t provide any arguments -- that won’t happen). Also, you can assume that all the command line arguments will be floating-point numbers, i.e., numbers with a decimal point, like 8.25.
is there anything wrong with the solution. the question are from java course Write a main...
is there anything wrong with the solution. the question are from java course Write a main method that will request the user to enter Strings using a JOptionPane input dialog. The method should continue accepting strings until the user types “STOP”.       Then, using a JOptionPane message dialog, tell the user how many of the strings begin and end with a digit. Answer: import javax.swing.*; public class IsAllLetters {     public static void main(String[] args) {         String input;         int count =...
You will write a program that loops until the user selects 0 to exit. In the...
You will write a program that loops until the user selects 0 to exit. In the loop the user interactively selects a menu choice to compress or decompress a file. There are three menu options: Option 0: allows the user to exit the program. Option 1: allows the user to compress the specified input file and store the result in an output file. Option 2: allows the user to decompress the specified input file and store the result in an...
Strings The example program below, with a few notes following, shows how strings work in C++....
Strings The example program below, with a few notes following, shows how strings work in C++. Example 1: #include <iostream> using namespace std; int main() { string s="eggplant"; string t="okra"; cout<<s[2]<<endl; cout<< s.length()<<endl; ​//prints 8 cout<<s.substr(1,4)<<endl; ​//prints ggpl...kind of like a slice, but the second num is the length of the piece cout<<s+t<<endl; //concatenates: prints eggplantokra cout<<s+"a"<<endl; cout<<s.append("a")<<endl; ​//prints eggplanta: see Note 1 below //cout<<s.append(t[1])<<endl; ​//an error; see Note 1 cout<<s.append(t.substr(1,1))<<endl; ​//prints eggplantak; see Note 1 cout<<s.find("gg")<<endl; if (s.find("gg")!=-1) cout<<"found...
-Data Structure in C++ (Review for C++) -using vector and class In this assignment you’re going...
-Data Structure in C++ (Review for C++) -using vector and class In this assignment you’re going to build a simple “register machine”, a kind of minimal computer that only supports storing a fixed number of values (i.e., no randomly-accessible “main memory”). Your machine will consist of an input loop that reads lines of input from the user and then executes them, stopping when the user quits (by executing the stop command). Each line of input consists of a command followed...
1. Vim commands: a. How do you auto indent your program? b. Explain what the following...
1. Vim commands: a. How do you auto indent your program? b. Explain what the following commands do: dd, y3, p, :set cindent (1 pt) VIM exercises These exercises on the computer need to be repeated by each student in the pair. This is to ensure that both students understand how to get around in Linux!!! For this part of the lab, you will create a .vimrc file that will help you develop your C++ programs using VIM. First, we...
PYTHON : Create a Email Address Parser (* Please do make comments*) Often times, you may...
PYTHON : Create a Email Address Parser (* Please do make comments*) Often times, you may be given a list of raw email addresses and be asked to generate meaningful information from such a list. This project involves parsing such a list and generating names and summary information from that list. The script, eparser.py, should: Open the file specified as the first argument to the script (see below) Read the file one line at a time (i.e., for line in...
Write a Python 3 program called “parse.py” using the template for a Python program that we...
Write a Python 3 program called “parse.py” using the template for a Python program that we covered in this module. Note: Use this mod7.txt input file. Name your output file “output.txt”. Build your program using a main function and at least one other function. Give your input and output file names as command line arguments. Your program will read the input file, and will output the following information to the output file as well as printing it to the screen:...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT