SlideShare a Scribd company logo
1 of 10
Download to read offline
Can someone put this code in a zip file. I tried running it last time it was answered but it did not
work.. Please and thanks in advance..
In my template for how to solve JH2, I assume you have seen the StringTokenizer which should
be covered in cps161. You can find it in the first 9 chapters of "Absolute Java" by Savitch. The
StringTokenizer is a simple class for parsing a String that has multiple words on it. Run the
following simple example to see what it does:
class participation: 5 points
file_operations(45 points)
Create a package named file_operations and a class named FileOperations which will receive
one or more command line pathnames to command files. Each command file will be opened and
processed line by line. Each line can contain one of the following commands:
? - This command will print out the legal commands available
createFile - The first string following "createFile" will be treated as a filename, and the
remaining strings will be written to the file separated by new lines.
printFile - The first string following "printFile" will be treated as a filename that will be opened
up and printed out to the screen.
lastModified - The first string following "lastModified" will be treated as a filename for which
we will print out the date when this file was last modified.
size - The first string following "size" will be treated as a filename for which we will print out
the number of bytes it contains.
rename - The first string following "rename" will be treated as the current filename and the
second string will be treated as the new filename we desire.
mkdir - The first string following "mkdir" will be treated as the name of a directory that should
be created.
delete - The first string following "delete" will be treated as the name of a file that should be
deleted.
list - The first string following "list" will be treated as the name of a directory for which we
want a list of the files it contains.
quit - exit program
Anything else is a bad command
For a non-existent command file, you would get something like:
For a good command file like cmd.txt
cmd.txt
Your output would look something like:
Here is a template that you can use.
Once you have your program written, I want you to add the following files to the top level of
your project and run the test that I request:
cmd1.txt
cmd2.txt
Run your program with the following command line:
cmd1.txt non-existent-file cmd2.txt
Insert the contents of your screen into the appropriate JH2 worksheet.
Please don't create a file with the name non-existent-file!!!
Solution
Hi,
PFB the class for the question. Please comment for any queries/feedbacks.
Thanks,
Anita
FileOperations.java
package file_operations;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import java.util.StringTokenizer;
// figure out your imports
public class FileOperations
{
StringTokenizer parseCommand;
private String currentLine;
public void delete()
{
// code for handling the delete command
// Make sure you check the return code from the
// File delete method to print out success/failure status
parseCommand = new StringTokenizer(currentLine);
String command = getNextToken();
String filename = getNextToken();
File file = new File(filename);
boolean isDeleted = file.delete();
if(isDeleted){
System.out.println("File is deleted.");
}
else{
System.out.println("Error in deleting the file");
}
}
public void rename()
{
// code for handling the rename command
// Make sure you check the return code from the
// File rename method to print out success/failure status
parseCommand = new StringTokenizer(currentLine);
String command = getNextToken();
String filename = getNextToken();
String newFileName = getNextToken();
File oldName = new File(filename);
File newName = new File(newFileName);
if (newName.exists()) newName.delete();
oldName.renameTo(newName);
System.out.println("renamed");
}
public void list()
{
// code for handling the list command
parseCommand = new StringTokenizer(currentLine);
String command = getNextToken();
String directoryName = getNextToken();
File folder = new File(directoryName);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
}
public void size()
{
// code for handling the size command
parseCommand = new StringTokenizer(currentLine);
String command = getNextToken();
String filename = getNextToken();
File file = new File(filename);
System.out.println("Size in bytes of "+filename+" is " + file.length());
}
public void lastModified()
{
// code for handling the lastModified command
parseCommand = new StringTokenizer(currentLine);
String command = getNextToken();
String filename = getNextToken();
File file = new File(filename);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("Last Modified of "+filename+" is " + sdf.format(file.lastModified()));
}
public void mkdir()
{
// code for handling the mkdir command
// Make sure you check the return code from the
// File mkdir method to print out success/failure status
parseCommand = new StringTokenizer(currentLine);
String command = getNextToken();
String directoryName = getNextToken();
File file = new File(directoryName);
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
}
public void createFile()
{
// code for handling the createFile command
parseCommand = new StringTokenizer(currentLine);
String command = getNextToken();
String filename = getNextToken();
FileWriter fw;
try {
fw = new FileWriter(filename);
String nextLine= getNextToken();
while(null!= nextLine){
//fw.append(" "); to print to a newline
fw.write(nextLine);
nextLine= getNextToken();
}
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(filename+" : File has been created. ");
}
public void printFile()
{
// code for handling the printFile command
parseCommand = new StringTokenizer(currentLine);
String command = getNextToken();
String filename = getNextToken();
System.out.println("Printing the contents of the file "+filename+" : ");
try {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
// Read br and store a line in 'data', print data
String data;
while((data = br.readLine()) != null)
{
//data = br.readLine( );
System.out.println(data);
}
} catch(IOException e) {
e.printStackTrace();
}
}
void printUsage()
{
// process the "?" command
}
// useful private routine for getting next string on the command line
private String getNextToken()
{
if (parseCommand.hasMoreTokens())
return parseCommand.nextToken();
else
return null;
}
// useful private routine for getting a File class from the next string on the command line
private File getFile()
{
File f = null;
String fileName = getNextToken();
if (fileName == null)
System.out.println("Missing a File name");
else
f = new File(fileName);
return f;
}
public boolean processCommandLine(String line)
{
// if line is not null, then setup the parseCommand StringTokenizer. Pull off the first string
// using getNextToken() and treat it as the "command" to be processed.
// It would be good to print out the command you are processing to make your output more
readable.
// If you are using at least java 1.7, you can use a switch statement on command.
// Otherwise, resort to if-then-else logic. Call the appropriate routine to process the
requested command:
// i.e. delete, rename, mkdir list, etc.
// return false if command is quit or the line is null, otherwise return true.
if(null!= line){
currentLine = line;
parseCommand = new StringTokenizer(line);
String command = getNextToken();
System.out.println(command +" : ");
switch(command){
case "createFile":
createFile();
break;
case "printFile":
printFile();
break;
case "lastModified":
lastModified();
break;
case "size":
size();
break;
case "rename":
rename();
break;
case "mkdir":
mkdir();
break;
case "delete":
delete();
break;
case "list":
list();
break;
case "quit":
break;
}
if(!"quit".equalsIgnoreCase(command)){
return true;
}
return false;
}
return false;
}
void processCommandFile(String commandFile)
{
// Open up a scanner based on the commandFile file name. Read the commands from this
file
// using the Scanner line by line. For each line read, call processCommandLine. Continue
reading
// from this file as long as processCommandLine returns true and there are more lines in the
file.
// At the end, close the Scanner.
File file = new File(commandFile);
boolean isPrevSuccess =true;
try {
Scanner sc = new Scanner(file);
while (isPrevSuccess && sc.hasNextLine()) {
String newLine = sc.nextLine();
isPrevSuccess = processCommandLine(newLine);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
FileOperations fo= new FileOperations();
for (int i=0; i < args.length; i++)
{
System.out.println("  ============ Processing " + args[i] +"
======================= ");
fo.processCommandFile(args[i]);
}
System.out.println("Done with FileOperations");
}
}
Sample execution in Command prompt:
G:Command_Projsrc>java file_operations.FileOperations
G:ProjectSpaceWorkspace_EclipseCheggChegg_Command_Projcmd1
.txt
============ Processing G:ProjectSpaceWorkspace_EclipseCheggChegg_Command_Pr
ojcmd1.txt =======================
? :
createFile :
file1.txt : File has been created.
printFile :
Printing the contents of the file file1.txt :
abcdefg
lastModified :
Last Modified of file1.txt is 02/06/2017 01:33:35
size :
Size in bytes of file1.txt is 7
rename :
renamed
mkdir :
Directory is created!
createFile :
dir/file2.txt : File has been created.
printFile :
Printing the contents of the file dir/file2.txt :
123456789
rename :
renamed
list :
Directory dir
File file1.txt
Directory file_operations
list :
File file2.txt
Done with FileOperations

More Related Content

Similar to Can someone put this code in a zip file. I tried running it last tim.pdf

(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docxajoy21
 
Linux_Commands.pdf
Linux_Commands.pdfLinux_Commands.pdf
Linux_Commands.pdfMarsMox
 
11 unix osx_commands
11 unix osx_commands11 unix osx_commands
11 unix osx_commandsMacinfosoft
 
Workshop on command line tools - day 1
Workshop on command line tools - day 1Workshop on command line tools - day 1
Workshop on command line tools - day 1Leandro Lima
 
ch06-file-processing.ppt
ch06-file-processing.pptch06-file-processing.ppt
ch06-file-processing.pptMahyuddin8
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docxtheodorelove43763
 
Common linux ubuntu commands overview
Common linux  ubuntu commands overviewCommon linux  ubuntu commands overview
Common linux ubuntu commands overviewAmeer Sameer
 
Introduction to linux day-3
Introduction to linux day-3Introduction to linux day-3
Introduction to linux day-3Gourav Varma
 
Need help with this java code. fill in lines where needed. Also, not.pdf
Need help with this java code. fill in lines where needed. Also, not.pdfNeed help with this java code. fill in lines where needed. Also, not.pdf
Need help with this java code. fill in lines where needed. Also, not.pdfrishabjain5053
 
[PDF] 2021 Termux basic commands list
[PDF] 2021 Termux basic commands list [PDF] 2021 Termux basic commands list
[PDF] 2021 Termux basic commands list nisivaasdfghj
 

Similar to Can someone put this code in a zip file. I tried running it last tim.pdf (20)

(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
(C Program to Simulate a UNIX-based filesystem) My goal is to implem.docx
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
Linux_Commands.pdf
Linux_Commands.pdfLinux_Commands.pdf
Linux_Commands.pdf
 
Linux intro 5 extra: makefiles
Linux intro 5 extra: makefilesLinux intro 5 extra: makefiles
Linux intro 5 extra: makefiles
 
50 most frequently used unix
50 most frequently used unix50 most frequently used unix
50 most frequently used unix
 
50 most frequently used unix
50 most frequently used unix50 most frequently used unix
50 most frequently used unix
 
11 unix osx_commands
11 unix osx_commands11 unix osx_commands
11 unix osx_commands
 
Linux
LinuxLinux
Linux
 
lec4.docx
lec4.docxlec4.docx
lec4.docx
 
Unix
UnixUnix
Unix
 
Workshop on command line tools - day 1
Workshop on command line tools - day 1Workshop on command line tools - day 1
Workshop on command line tools - day 1
 
Linux intro 4 awk + makefile
Linux intro 4  awk + makefileLinux intro 4  awk + makefile
Linux intro 4 awk + makefile
 
ch06-file-processing.ppt
ch06-file-processing.pptch06-file-processing.ppt
ch06-file-processing.ppt
 
Linux commands
Linux commandsLinux commands
Linux commands
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
 
Common linux ubuntu commands overview
Common linux  ubuntu commands overviewCommon linux  ubuntu commands overview
Common linux ubuntu commands overview
 
Introduction to linux day-3
Introduction to linux day-3Introduction to linux day-3
Introduction to linux day-3
 
Need help with this java code. fill in lines where needed. Also, not.pdf
Need help with this java code. fill in lines where needed. Also, not.pdfNeed help with this java code. fill in lines where needed. Also, not.pdf
Need help with this java code. fill in lines where needed. Also, not.pdf
 
[PDF] 2021 Termux basic commands list
[PDF] 2021 Termux basic commands list [PDF] 2021 Termux basic commands list
[PDF] 2021 Termux basic commands list
 
IntroCommandLine.ppt
IntroCommandLine.pptIntroCommandLine.ppt
IntroCommandLine.ppt
 

More from fedosys

If messages are being sent from your email account without your know.pdf
If messages are being sent from your email account without your know.pdfIf messages are being sent from your email account without your know.pdf
If messages are being sent from your email account without your know.pdffedosys
 
Identify some of the postmodern trends movements that women artist .pdf
Identify some of the postmodern trends movements that women artist .pdfIdentify some of the postmodern trends movements that women artist .pdf
Identify some of the postmodern trends movements that women artist .pdffedosys
 
i need the executable file of this program (.exe) This is Assembly.pdf
i need the executable file of this program (.exe) This is Assembly.pdfi need the executable file of this program (.exe) This is Assembly.pdf
i need the executable file of this program (.exe) This is Assembly.pdffedosys
 
Help me fix the error shown above in my code of image.cpp please~I.pdf
Help me fix the error shown above in my code of image.cpp please~I.pdfHelp me fix the error shown above in my code of image.cpp please~I.pdf
Help me fix the error shown above in my code of image.cpp please~I.pdffedosys
 
Explain how the format of the mark-up language differs from the docu.pdf
Explain how the format of the mark-up language differs from the docu.pdfExplain how the format of the mark-up language differs from the docu.pdf
Explain how the format of the mark-up language differs from the docu.pdffedosys
 
Here is the given code, and the things I need to be done. Ive post.pdf
Here is the given code, and the things I need to be done. Ive post.pdfHere is the given code, and the things I need to be done. Ive post.pdf
Here is the given code, and the things I need to be done. Ive post.pdffedosys
 
Each student in my class was given bodily fluids. Everyone was n.pdf
Each student in my class was given bodily fluids. Everyone was n.pdfEach student in my class was given bodily fluids. Everyone was n.pdf
Each student in my class was given bodily fluids. Everyone was n.pdffedosys
 
Hello everyone,Im actually working on a fast food order program..pdf
Hello everyone,Im actually working on a fast food order program..pdfHello everyone,Im actually working on a fast food order program..pdf
Hello everyone,Im actually working on a fast food order program..pdffedosys
 
Describe the attributes that make a vision meaningful to stakeholder.pdf
Describe the attributes that make a vision meaningful to stakeholder.pdfDescribe the attributes that make a vision meaningful to stakeholder.pdf
Describe the attributes that make a vision meaningful to stakeholder.pdffedosys
 
Create a C program which auto-completes suggestions when beginning t.pdf
Create a C program which auto-completes suggestions when beginning t.pdfCreate a C program which auto-completes suggestions when beginning t.pdf
Create a C program which auto-completes suggestions when beginning t.pdffedosys
 
Compare the DHCP and DHCPv6SolutionThe comparison between the .pdf
Compare the DHCP and DHCPv6SolutionThe comparison between the .pdfCompare the DHCP and DHCPv6SolutionThe comparison between the .pdf
Compare the DHCP and DHCPv6SolutionThe comparison between the .pdffedosys
 
Consider in a given economy For a given time period the following in.pdf
Consider in a given economy For a given time period the following in.pdfConsider in a given economy For a given time period the following in.pdf
Consider in a given economy For a given time period the following in.pdffedosys
 
Background Many cities such as Detroit, MI have been in the news re.pdf
Background Many cities such as Detroit, MI have been in the news re.pdfBackground Many cities such as Detroit, MI have been in the news re.pdf
Background Many cities such as Detroit, MI have been in the news re.pdffedosys
 
Assignment 1. List the three visual elements Brieny descrbe each. 2 W.pdf
Assignment 1. List the three visual elements Brieny descrbe each. 2 W.pdfAssignment 1. List the three visual elements Brieny descrbe each. 2 W.pdf
Assignment 1. List the three visual elements Brieny descrbe each. 2 W.pdffedosys
 
A. Intergenic sequences make up 60 of the human genome. Where do t.pdf
A. Intergenic sequences make up 60 of the human genome. Where do t.pdfA. Intergenic sequences make up 60 of the human genome. Where do t.pdf
A. Intergenic sequences make up 60 of the human genome. Where do t.pdffedosys
 
a) How can habitat selection and sexual selection drive sympatric sp.pdf
a) How can habitat selection and sexual selection drive sympatric sp.pdfa) How can habitat selection and sexual selection drive sympatric sp.pdf
a) How can habitat selection and sexual selection drive sympatric sp.pdffedosys
 
A common test of balances in a revenue cycle is the inquiry of manage.pdf
A common test of balances in a revenue cycle is the inquiry of manage.pdfA common test of balances in a revenue cycle is the inquiry of manage.pdf
A common test of balances in a revenue cycle is the inquiry of manage.pdffedosys
 
7. Recently, Skooterville has experienced a large growth in populati.pdf
7. Recently, Skooterville has experienced a large growth in populati.pdf7. Recently, Skooterville has experienced a large growth in populati.pdf
7. Recently, Skooterville has experienced a large growth in populati.pdffedosys
 
50mL of a 0.1000 M aqueous solution of hydrazoic acid (HN3, Ka=1.91.pdf
50mL of a 0.1000 M aqueous solution of hydrazoic acid (HN3, Ka=1.91.pdf50mL of a 0.1000 M aqueous solution of hydrazoic acid (HN3, Ka=1.91.pdf
50mL of a 0.1000 M aqueous solution of hydrazoic acid (HN3, Ka=1.91.pdffedosys
 
4. For each of the following electrochemical cells i. Identify the a.pdf
4. For each of the following electrochemical cells i. Identify the a.pdf4. For each of the following electrochemical cells i. Identify the a.pdf
4. For each of the following electrochemical cells i. Identify the a.pdffedosys
 

More from fedosys (20)

If messages are being sent from your email account without your know.pdf
If messages are being sent from your email account without your know.pdfIf messages are being sent from your email account without your know.pdf
If messages are being sent from your email account without your know.pdf
 
Identify some of the postmodern trends movements that women artist .pdf
Identify some of the postmodern trends movements that women artist .pdfIdentify some of the postmodern trends movements that women artist .pdf
Identify some of the postmodern trends movements that women artist .pdf
 
i need the executable file of this program (.exe) This is Assembly.pdf
i need the executable file of this program (.exe) This is Assembly.pdfi need the executable file of this program (.exe) This is Assembly.pdf
i need the executable file of this program (.exe) This is Assembly.pdf
 
Help me fix the error shown above in my code of image.cpp please~I.pdf
Help me fix the error shown above in my code of image.cpp please~I.pdfHelp me fix the error shown above in my code of image.cpp please~I.pdf
Help me fix the error shown above in my code of image.cpp please~I.pdf
 
Explain how the format of the mark-up language differs from the docu.pdf
Explain how the format of the mark-up language differs from the docu.pdfExplain how the format of the mark-up language differs from the docu.pdf
Explain how the format of the mark-up language differs from the docu.pdf
 
Here is the given code, and the things I need to be done. Ive post.pdf
Here is the given code, and the things I need to be done. Ive post.pdfHere is the given code, and the things I need to be done. Ive post.pdf
Here is the given code, and the things I need to be done. Ive post.pdf
 
Each student in my class was given bodily fluids. Everyone was n.pdf
Each student in my class was given bodily fluids. Everyone was n.pdfEach student in my class was given bodily fluids. Everyone was n.pdf
Each student in my class was given bodily fluids. Everyone was n.pdf
 
Hello everyone,Im actually working on a fast food order program..pdf
Hello everyone,Im actually working on a fast food order program..pdfHello everyone,Im actually working on a fast food order program..pdf
Hello everyone,Im actually working on a fast food order program..pdf
 
Describe the attributes that make a vision meaningful to stakeholder.pdf
Describe the attributes that make a vision meaningful to stakeholder.pdfDescribe the attributes that make a vision meaningful to stakeholder.pdf
Describe the attributes that make a vision meaningful to stakeholder.pdf
 
Create a C program which auto-completes suggestions when beginning t.pdf
Create a C program which auto-completes suggestions when beginning t.pdfCreate a C program which auto-completes suggestions when beginning t.pdf
Create a C program which auto-completes suggestions when beginning t.pdf
 
Compare the DHCP and DHCPv6SolutionThe comparison between the .pdf
Compare the DHCP and DHCPv6SolutionThe comparison between the .pdfCompare the DHCP and DHCPv6SolutionThe comparison between the .pdf
Compare the DHCP and DHCPv6SolutionThe comparison between the .pdf
 
Consider in a given economy For a given time period the following in.pdf
Consider in a given economy For a given time period the following in.pdfConsider in a given economy For a given time period the following in.pdf
Consider in a given economy For a given time period the following in.pdf
 
Background Many cities such as Detroit, MI have been in the news re.pdf
Background Many cities such as Detroit, MI have been in the news re.pdfBackground Many cities such as Detroit, MI have been in the news re.pdf
Background Many cities such as Detroit, MI have been in the news re.pdf
 
Assignment 1. List the three visual elements Brieny descrbe each. 2 W.pdf
Assignment 1. List the three visual elements Brieny descrbe each. 2 W.pdfAssignment 1. List the three visual elements Brieny descrbe each. 2 W.pdf
Assignment 1. List the three visual elements Brieny descrbe each. 2 W.pdf
 
A. Intergenic sequences make up 60 of the human genome. Where do t.pdf
A. Intergenic sequences make up 60 of the human genome. Where do t.pdfA. Intergenic sequences make up 60 of the human genome. Where do t.pdf
A. Intergenic sequences make up 60 of the human genome. Where do t.pdf
 
a) How can habitat selection and sexual selection drive sympatric sp.pdf
a) How can habitat selection and sexual selection drive sympatric sp.pdfa) How can habitat selection and sexual selection drive sympatric sp.pdf
a) How can habitat selection and sexual selection drive sympatric sp.pdf
 
A common test of balances in a revenue cycle is the inquiry of manage.pdf
A common test of balances in a revenue cycle is the inquiry of manage.pdfA common test of balances in a revenue cycle is the inquiry of manage.pdf
A common test of balances in a revenue cycle is the inquiry of manage.pdf
 
7. Recently, Skooterville has experienced a large growth in populati.pdf
7. Recently, Skooterville has experienced a large growth in populati.pdf7. Recently, Skooterville has experienced a large growth in populati.pdf
7. Recently, Skooterville has experienced a large growth in populati.pdf
 
50mL of a 0.1000 M aqueous solution of hydrazoic acid (HN3, Ka=1.91.pdf
50mL of a 0.1000 M aqueous solution of hydrazoic acid (HN3, Ka=1.91.pdf50mL of a 0.1000 M aqueous solution of hydrazoic acid (HN3, Ka=1.91.pdf
50mL of a 0.1000 M aqueous solution of hydrazoic acid (HN3, Ka=1.91.pdf
 
4. For each of the following electrochemical cells i. Identify the a.pdf
4. For each of the following electrochemical cells i. Identify the a.pdf4. For each of the following electrochemical cells i. Identify the a.pdf
4. For each of the following electrochemical cells i. Identify the a.pdf
 

Recently uploaded

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 

Recently uploaded (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

Can someone put this code in a zip file. I tried running it last tim.pdf

  • 1. Can someone put this code in a zip file. I tried running it last time it was answered but it did not work.. Please and thanks in advance.. In my template for how to solve JH2, I assume you have seen the StringTokenizer which should be covered in cps161. You can find it in the first 9 chapters of "Absolute Java" by Savitch. The StringTokenizer is a simple class for parsing a String that has multiple words on it. Run the following simple example to see what it does: class participation: 5 points file_operations(45 points) Create a package named file_operations and a class named FileOperations which will receive one or more command line pathnames to command files. Each command file will be opened and processed line by line. Each line can contain one of the following commands: ? - This command will print out the legal commands available createFile - The first string following "createFile" will be treated as a filename, and the remaining strings will be written to the file separated by new lines. printFile - The first string following "printFile" will be treated as a filename that will be opened up and printed out to the screen. lastModified - The first string following "lastModified" will be treated as a filename for which we will print out the date when this file was last modified. size - The first string following "size" will be treated as a filename for which we will print out the number of bytes it contains. rename - The first string following "rename" will be treated as the current filename and the second string will be treated as the new filename we desire. mkdir - The first string following "mkdir" will be treated as the name of a directory that should be created. delete - The first string following "delete" will be treated as the name of a file that should be deleted. list - The first string following "list" will be treated as the name of a directory for which we want a list of the files it contains. quit - exit program Anything else is a bad command For a non-existent command file, you would get something like: For a good command file like cmd.txt cmd.txt Your output would look something like: Here is a template that you can use.
  • 2. Once you have your program written, I want you to add the following files to the top level of your project and run the test that I request: cmd1.txt cmd2.txt Run your program with the following command line: cmd1.txt non-existent-file cmd2.txt Insert the contents of your screen into the appropriate JH2 worksheet. Please don't create a file with the name non-existent-file!!! Solution Hi, PFB the class for the question. Please comment for any queries/feedbacks. Thanks, Anita FileOperations.java package file_operations; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Scanner; import java.util.StringTokenizer; // figure out your imports public class FileOperations { StringTokenizer parseCommand; private String currentLine;
  • 3. public void delete() { // code for handling the delete command // Make sure you check the return code from the // File delete method to print out success/failure status parseCommand = new StringTokenizer(currentLine); String command = getNextToken(); String filename = getNextToken(); File file = new File(filename); boolean isDeleted = file.delete(); if(isDeleted){ System.out.println("File is deleted."); } else{ System.out.println("Error in deleting the file"); } } public void rename() { // code for handling the rename command // Make sure you check the return code from the // File rename method to print out success/failure status parseCommand = new StringTokenizer(currentLine); String command = getNextToken(); String filename = getNextToken(); String newFileName = getNextToken(); File oldName = new File(filename); File newName = new File(newFileName); if (newName.exists()) newName.delete(); oldName.renameTo(newName); System.out.println("renamed"); } public void list() { // code for handling the list command parseCommand = new StringTokenizer(currentLine);
  • 4. String command = getNextToken(); String directoryName = getNextToken(); File folder = new File(directoryName); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { System.out.println("File " + listOfFiles[i].getName()); } else if (listOfFiles[i].isDirectory()) { System.out.println("Directory " + listOfFiles[i].getName()); } } } public void size() { // code for handling the size command parseCommand = new StringTokenizer(currentLine); String command = getNextToken(); String filename = getNextToken(); File file = new File(filename); System.out.println("Size in bytes of "+filename+" is " + file.length()); } public void lastModified() { // code for handling the lastModified command parseCommand = new StringTokenizer(currentLine); String command = getNextToken(); String filename = getNextToken(); File file = new File(filename); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); System.out.println("Last Modified of "+filename+" is " + sdf.format(file.lastModified())); } public void mkdir() { // code for handling the mkdir command // Make sure you check the return code from the // File mkdir method to print out success/failure status
  • 5. parseCommand = new StringTokenizer(currentLine); String command = getNextToken(); String directoryName = getNextToken(); File file = new File(directoryName); if (!file.exists()) { if (file.mkdir()) { System.out.println("Directory is created!"); } else { System.out.println("Failed to create directory!"); } } } public void createFile() { // code for handling the createFile command parseCommand = new StringTokenizer(currentLine); String command = getNextToken(); String filename = getNextToken(); FileWriter fw; try { fw = new FileWriter(filename); String nextLine= getNextToken(); while(null!= nextLine){ //fw.append(" "); to print to a newline fw.write(nextLine); nextLine= getNextToken(); } fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(filename+" : File has been created. "); } public void printFile()
  • 6. { // code for handling the printFile command parseCommand = new StringTokenizer(currentLine); String command = getNextToken(); String filename = getNextToken(); System.out.println("Printing the contents of the file "+filename+" : "); try { FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); // Read br and store a line in 'data', print data String data; while((data = br.readLine()) != null) { //data = br.readLine( ); System.out.println(data); } } catch(IOException e) { e.printStackTrace(); } } void printUsage() { // process the "?" command } // useful private routine for getting next string on the command line private String getNextToken() { if (parseCommand.hasMoreTokens()) return parseCommand.nextToken(); else return null; } // useful private routine for getting a File class from the next string on the command line private File getFile()
  • 7. { File f = null; String fileName = getNextToken(); if (fileName == null) System.out.println("Missing a File name"); else f = new File(fileName); return f; } public boolean processCommandLine(String line) { // if line is not null, then setup the parseCommand StringTokenizer. Pull off the first string // using getNextToken() and treat it as the "command" to be processed. // It would be good to print out the command you are processing to make your output more readable. // If you are using at least java 1.7, you can use a switch statement on command. // Otherwise, resort to if-then-else logic. Call the appropriate routine to process the requested command: // i.e. delete, rename, mkdir list, etc. // return false if command is quit or the line is null, otherwise return true. if(null!= line){ currentLine = line; parseCommand = new StringTokenizer(line); String command = getNextToken(); System.out.println(command +" : "); switch(command){ case "createFile": createFile(); break; case "printFile": printFile(); break; case "lastModified": lastModified(); break; case "size":
  • 8. size(); break; case "rename": rename(); break; case "mkdir": mkdir(); break; case "delete": delete(); break; case "list": list(); break; case "quit": break; } if(!"quit".equalsIgnoreCase(command)){ return true; } return false; } return false; } void processCommandFile(String commandFile) { // Open up a scanner based on the commandFile file name. Read the commands from this file // using the Scanner line by line. For each line read, call processCommandLine. Continue reading // from this file as long as processCommandLine returns true and there are more lines in the file. // At the end, close the Scanner. File file = new File(commandFile); boolean isPrevSuccess =true;
  • 9. try { Scanner sc = new Scanner(file); while (isPrevSuccess && sc.hasNextLine()) { String newLine = sc.nextLine(); isPrevSuccess = processCommandLine(newLine); } sc.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void main(String[] args) { FileOperations fo= new FileOperations(); for (int i=0; i < args.length; i++) { System.out.println(" ============ Processing " + args[i] +" ======================= "); fo.processCommandFile(args[i]); } System.out.println("Done with FileOperations"); } } Sample execution in Command prompt: G:Command_Projsrc>java file_operations.FileOperations G:ProjectSpaceWorkspace_EclipseCheggChegg_Command_Projcmd1 .txt ============ Processing G:ProjectSpaceWorkspace_EclipseCheggChegg_Command_Pr ojcmd1.txt ======================= ? : createFile : file1.txt : File has been created. printFile : Printing the contents of the file file1.txt :
  • 10. abcdefg lastModified : Last Modified of file1.txt is 02/06/2017 01:33:35 size : Size in bytes of file1.txt is 7 rename : renamed mkdir : Directory is created! createFile : dir/file2.txt : File has been created. printFile : Printing the contents of the file dir/file2.txt : 123456789 rename : renamed list : Directory dir File file1.txt Directory file_operations list : File file2.txt Done with FileOperations