Likes

Java Lab_14_Ans_3

3. Write a Java main that creates a PathMatcher class and uses FileVisitor to recursively delete a file or directory pattern.

SOLUTION


1. Open the project RecursiveOeleteExercise m the practices director.-.
2. Expand the Source Packages folders.
3. Open the Delete .java class file. This is the class that contains the nain method. The mam class accepts two arguments: the first is the starting path and the other the pattern to delete.
4. You must code the remainder of this class. Look at the comments for hurts as to what to do.
a. Start by creating a PathMatcher object from tire search string passed in as tire second argument. To obtain a PatW’atcher instance, you will need to use tire FileSystems class to get a path matcher instance from tire default file system.
b. Create a Path object from tire first argument.
c. If tire starting path is a file, check it against tire pattern using tire PatW’atcher instance that you created. If there is a match, delete tire file, and then terminate tire application.
d. If tire starting path is a directory, create an instance of tire CeleteFile-ree With the Startmg directory and tire Pathllatcher object as initial arguments in tire constructor. Pass tire startmg directory and the file tree to a Files..isl<=ile7ree method to recursively look for the pattern to delete.
e. Fix air.- missing unports.
f. Save the Delete class.
5. Open the Delete'ileTree class file. This class unplements 'ileVisitor. This class recursively looks for instances of files or directories that match the Psth'iatcher object passed into the constructor. This class is complete with the exception of the delete method.
a. The delete method is called by the preVisitDirectory and
vis it File methods. You must check whether the file or directory reached by these methods matches the pattern.
b. We only want to match the path name at the node, so use the Path. getFile'Jane method to obtain the file name at the end of the full path.
c. If the name matches, use the Files, delete method to attempt to delete the file pattern and print a result statement, or print an error if an lOExcepticn is thrown.
d. Save the CeleteFileTree class.
6. Run the Delete application using a temporary directory.
a. For example, if you completed the first practice, you can delete all the Java class files from the D:\Tenp directory.
b. Right-click the project and select Properties.
c. Click Run and enter the following in the Arguments text field: D:\Tenp\exanples ♦.class
d. Run the project.

Java Lab_14_Ans_2

2. Write Java classes that use the FileVisitor class to recursively copy one directory to another.



SOLUTION


1. Open the project RecursiveCopyExercise in the directory D:\labs\ll-NI0.2\practices.
2. Expand the Source Package* folder and subfolders and look at the Copy, java class.
a. Note that the Copy, java class contains the mair method.
b. The application takes two arguments, a source and target paths.
c. If the target file or directory exists, the user is prompted whether to overwrite.
d. If the answer is yes (or the letter y). the method continues.
e. An instance of the CopyFileTree class is created with the source and target.
f. This mstance is then passed to the walkFileTree method (with the source Path object).
You will need to prcrnde method bodies for the methods in the CopyFileTree. java class.
3. Open the CopyFileTree. java class.
a. This class unplements the 'ileVisitcr interface. Note that FileVisitcr is a generic interface, and this interface is boxed with the Rath class. This allows the interface to denne the t>pe of the arguments passed to its methods.
b. The CopyFileTree implements all the methods denned by FiieVisitor.
c. Your task is to write method bodies for the oreVisitDirectory and visitFile methods. You will not need the po;tVi; it Directory method. and you have been provided a method body for the visitrileFailed metliod.
4. Write tlie metliod body for preVicitDirectory. This metliod is called for the starting node of tlie tree and every subdirectory. Therefore, you should copy tlie directory of tlie source to tlie target. If tlie file already exists, you can ignore that exception (because you are domg tlie cops- because tlie user elected to overwrite.)
a. Start by creatmg a new directors- that is relative to tlie target passed in. but is tlie node name from tlie source. The metliod call to do this is:
Path newdir = target.resolve(source.relativi:e(dir));
b. In a try block cops- tlie directors- passed to tlie oreVicitDirectory metliod to tlie newdir that you created.
c. You can ignore any File Already Exacts Except ion thrown, because you are overwrituig any existmg folders and files in tins cops-.
d. Catch air.- other IOExcepticnc. and use the 51CIP_SUBTPEE return to avoid repeated errors.
5. Write tlie metliod bods- for tlie /isitFiie metliod. This metliod is called when tlie node reached is a file. The file is passed as an argument to tlie metliod.
a. As with tlie preVisitOirectory. you must rationalize tlie file reached (source path) with tlie path that you wanted for tlie target. Use tlie same metliod call as above (only usmg -ile instead of dir):
b. As m the sreVisitDirectory method use the 'iles.copy method in a try block. Mala sure that you pass 3EPLACE_EXISTING m as an option to overwrite air.- existing file in the directory.
c. Catch air.- lOExceptico thrown and report an error.
d. Fix air.- missing unports.
e. Save your class.
6. Test your application by copymg a directory (ideally with subdirectories) to another location on the disk. For example, cops- the D: \labs\ll-NI0.2 directory to D: \Temp.
a. Right-click the project and select Properties.
b. Click Run.
c. Enter the following as Arguments:
D:\labs\ll-NI0.2 D:\Terp
d Click OK.
7. Run the project and you should see the follow mg message:
Successfully copied D:\labs\ll-NI0.2 to D:\Tenp
a. Run the project agaui and you should be prompted:
Target directory exists, ^.-erv.rite existing files? (yes/oo):

Java Lab_14_Ans_1

1. Use the Files. readAllLines method to read the entire contents of two files: a form template, and a list of names to send form letters to. After creating a form letter with a name from the name list, you will use the Files, write method to create the custom letter. You will also use the Pattern and Matcher classes that you saw in the "String Processing" lesson.


SOLUTION


1. Open the file FornTerplate in the resource: director.-.
Note that this is a form letter with a string <NAHE> that will be replaced by a name from the name list file.
2. Open the file NamesList.txt in the resources directory.
a. This file contains the names to send the form letters to.
b. Add your name to the end of the list.
c. Save the file.
3. Open the project ForntetterM-iier in the practices directory.
4. Expand the FornietterKricer class. Notice that this class contains the mam method, and that the application requires two parameters: One is the path to the form letter template, and the second is the path to the file containing the list of names to substitute in the form letter.
a. After checking for a valid number of arguments, the mam method then checks to see whether the Path objects point to valid files.
b. The mam method creates an instance of the FilcMerge class with the form letter Path object and the list of names =ath object.
c. In a try block the mam method calls the write! lergedF©™ method of the FileMerge class. This is the method that you will write in this practice.
5. Expand the FileMerge class.
a. Note the write!tergedForns method is empty. This is the method that you will write m this practice.
b. The merge Name method uses the Pattern object defined in the field declarations to replace the string from the form template (first argument) with a name from the name list (second argument). It returns a Strmg. For example, it replaces "Dear <MAME>,” with "Dear Wilscn Ball,”.
c. The naiToker method returns a boolean to indicate whether the string pa»>ed m contains the token This is useful to identify which string has the token to replace with the name from the name list.
6. Code the writeMergedForms method. The overall plan for this method is to read in the entire form letter, line by line, and then read in the entire list of names and merge the names with the form letter, replacing the placeholder in the template with a name from the list and then writing that out as a file. The net result should be that if you have ten names m the name list, you should end up with ten custom letter fries addressed to the names from the name list. These ten files will be written to the resources director.-.
a. Read in all of the Imes of the form letter into the -ormLet-er field, and all of the Imes from the name list into the nans List field.
Note: Because i%rite!lergedForni throws IC€xcepticn. you do not need to put these statements into a try block. The caller of this method is responsible for handlmg air.- exceptions thrown.
b. Create a ■'or loop to iterate through the list of names (nareList) strings.
c. Inside this for loop, create a new List object to Isold the strings of the form letter. You need tins new Lis-: to hold the modified form template strings to write out.
d. Still inside the -or loop, you will need to create a name for the custom letter. One easy way to do this is to use the name from the name list. You should replace air.- spaces in the name with underscores for readability of the file name. Create a new Path object relative to the form template path.
e. Create another -or loop, nested in the first loop, to iterate through the lines of the form template and look for the token string
(" NAME ”) to replace with the String name from the naneList. Use the haiTo<en method to look for the String that contains the token string and replace that string with one containing the name from the naneList. Use the mergeNane method to create the new String. Add the modified String and all of the Other Strings from the -ormLerser to the new custonLetter List.
f. Still inside the first ■'or loop, write the modified List of Strings that represents the customized form letter to the file system by using the 'lies...rite method. Prmt a message that the file write was successful and close the outer for loop.
g. Save the File!-«rge class.
7. Modify the FomLetterUriter project to pass the form letter file and the name list file to the mam method.
a. Right-click the project and select Properties.
b. Select Run.
c. In the Arguments text field, enter:
D:\labs\resources\=or«n7emplane. tx« D:\labs\resources\NamesList.txt
d. Click OK.
S. Run the project. You should >ee new files created with the names from the name list. Each file should be customized with the name from the name list. For example, the Tcm_McGinn.txt file should contain:
Dear Ton McGinn,
It has ccme to our attention that you would like to prove your lava Skills. May we reconnend that you consider certification fron Oracle? Oracle has globally recognised Certification exans that will test your lava krsowlesge and skills.
Start with the Oracle Certified lava Associate exam, and then continue to the Oracle Certified lava Prograrner Professional for a ccrrplete certification profile.

Java Lab_12_Ans_3

Write a Java program to perform the following tasks:
Reading a text file
Writing in a text file
Searching in a text file

solution

1. Create a Java application. Chapter10_Exercise03.
2. Create a class. FileOperation. in the Java application. Chapter10_Exercise03.
3. Replace the existing code in the FileOperation.java file with the following code:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
public class FileOperation {
public void readFile() {
Scanner sc = new Scanner(System.in);
String fileName;
System.out.print("Enter the text file name that you want to read from the D:\\ drive: "); fileName = sc.nextLine();
try (BufferedReader br = new BufferedReader(new FileReader("D:\\" + fileName + ".txt "))) {
String s;
System.out.println("\nThe " + fileName + " contains the following text:\n");
System.out.println
while ((s = br.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
System.out.println("File does not exists."); menu();
}
}
public void writeFile() {
Scanner sc = new Scanner(System.in);
String fileName, text;
System.out.print("Enter the file name from the D:\\ drive in which you 'want to write: "); fileName = sc.nextLine ();
System.out.print("Enter the text you want to write in the " + fileName + " file: "); text = sc.nextLine();
try {
FileWriter fos = new FileWriter("D:\\" + fileName + ".txt", true);
BufferedWriter bw = new BufferedWriter(fos); bw.newLine(); bw.write(text);
bw.close (); fos.close();
System.out.println("\nThe text has been added in the file");
} catch (Exception e) {
System.out.println("File does not exists"); menu();
}
}
public void searchFileO {
Scanner sc = new Scanner(System.in);
String fileName, text; int counter = 0, flag = 0;
System.out.print("Enter the file name from the D:\\ drive in which you want to search: ");
fileName = sc.nextLine();
System.out.print("Enter the string you want to search in the " + fileName + " file: "); text = sc.nextLine();
try (BufferedReader br = new BufferedReader(new FileReader("D:\\" + fileName + ".txt "))) {
String s;
while ((s = br.readLine()) != null) {
String splitData() = s.split(" ");
{
for (int i = 0; i < splitData.length; i++) if (splitData(i].equals(text)) {
if (splitData(i].equals(text)) {
counter++; flag = 1;
}
}
} catch (Exception e) {
System.out.println("File does not exits"); menu () ;
}
if (flag == 1) (
if (counter == 1) {
System.out.println("\"" + text + "\" has occured " + counter + " time");
} else {
System.out.println("\"" + text + "\" has occured " + counter + " times");
}
} else {
System.out.println("The entered word doest not exist in the file.");
}

public void menu() { int option;
Scanner sc = new Scanner(System.in);
System, out. print In (" \n-----Menu---------") ;
System.out.println("1. Reading");
System.out.println("2. Writing");
System.out.println("3. Searching");
System.out.println("4. Exit");
System.out.print("\nChoose the option: ")
option = sc.nextInt();
switch (option) { case 1:
readFile(); menu(); break; case 2:
writeFile(); menu(); break; case 3:
searchFile();
menu(); break; case 4:
System.exit(0); break; default:
System.out.println("Incorrect menu option");
menu(); break;
}
}
public static void main(String!) args) {
FileOperation fo = new FileOperation() fo.menu();
}
}
4. Compile and execute the Chapter!0_Exercise03 Java application.