Question

In: Computer Science

Part 1 readFile(String filename) In this method you are passed a String with the name of...

Part 1 readFile(String filename)

In this method you are passed a String with the name of a file. This method will read the file in line by line and store each line in a String array. This String array is then returned. An example is shown below.

File Contents:
Purple Rain by Prince
I never meant to cause you any sorrow
I never meant to cause you any pain
I only wanted one time to see you laughing
I only want to see you laughing in the purple rain

String Array Contents:
[0]: Purple Rain by Prince
[1]: I never meant to cause you any sorrow
[2]: I never meant to cause you any pain
[3]: I only wanted one time to see you laughing
[4]: I only want to see you laughing in the purple rain

In order to do this, you will need:

  • a String array
  • an int that keeps track of how many lines there are in a file
  • a File Object
  • a Scanner Object

Assume that the String array holds a max of 1000 elements. Notice that there are three lines of code written at the bottom. DO NOT MODIFY THESE LINES.This code is copying your String array into a new array with the same amount of elements as there are lines in the file. Since this code is written for you, it assumes that your String array is named lines and that the int that keeps track of the amount of lines is named lineCounter. You will loop through and parse this file with the use of the Scanner and File Object and store each line in the String array while also counting each line.

Hints

  • How can a Scanner be used to know when the file ends?
  • You will need a try/catch block.

Part 2 reverseFile(String[] parsedFile, String filename)

This method takes a String array that has lines of a file in it and a filename. This method will write the contents of the String array in reverse order to the file passed. The writing will be done with a PrintWriter. Here is an example.

String Array Content:
[0]: Purple Rain by Prince
[1]: I never meant to cause you any sorrow
[2]: I never meant to cause you any pain
[3]: I only wanted one time to see you laughing
[4]: I only want to see you laughing in the purple rain

Files Contents:
I only want to see you laughing in the purple rain
I only wanted one time to see you laughing
I never meant to cause you any pain
I never meant to cause you any sorrow
Purple Rain by Prince

Hint

  • You will need a try/catch block.

Part 3 logFile(String[] parsedFile, String filename)

This method takes a String array that has lines of a file in it and a filename. This method will write contents of the String array to a file. However, It will only write the lines that contain “LOG”. Other lines will be skipped over. Here is an example.

String Array Content:
[0]: LOG username: happy_cat31
[1]: password: MrMuffins1234
[2]: LOG username: sad_panda
[3]: password: BambooLover83

Files Contents:
LOG username: happy_cat31
LOG username: sad_panda 

Hints

  • What String method could help determine if a file contains “LOG”? String Java Doc
  • You will need a try/catch block.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class FileIO {

//Part 1
public static String[] readFile(String filename) {

//Student Code Here

//3 lines below given to students. DO NOT MODIFY
String[] rtn = new String[lineCounter];
System.arraycopy(lines, 0, rtn, 0, lineCounter);
return rtn;
}


//Part 2
public static void reverseFile(String[] parsedFile, String filename) {

//Student Code Here

}

//Part 3
public static void logFile(String[] parsedFile, String filename) {

//Student Code Here

}


public static void main(String[] args) {

}

}

Solutions

Expert Solution

Short Summary:

Implemented the program as per requirement

Attached source code and sample output

**************Please do upvote to appreciate our time. Thank you!******************

Source Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class FileIO {

   //Part 1
   public static String[] readFile(String filename) {

       //Student Code Here
       int lineCounter=0;
       //Create a initial string array
       String[] lines = new String[1000];
       Scanner input;
       try {
           //Read file using scanner
           input = new Scanner(new File(filename));

           //Iterate until file has a line
           while(input.hasNext())
           {
               lines[lineCounter]=input.nextLine();
               lineCounter++;
           }
           //3 lines below given to students. DO NOT MODIFY
           String[] rtn = new String[lineCounter];
           System.arraycopy(lines, 0, rtn, 0, lineCounter);
           input.close();
           return rtn;
       } catch (FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }

       return null;

   }


   //Part 2
   public static void reverseFile(String[] parsedFile, String filename) {

       //Student Code Here
       try {
           //Create a Writer object
           PrintWriter writer=new PrintWriter(new File(filename));
           for(int i=parsedFile.length-1;i>=0;i--)
           {
               writer.write(parsedFile[i]+"\n");
           }
           writer.close();

       } catch (FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }


   }

   //Part 3
   public static void logFile(String[] parsedFile, String filename) {


       //Student Code Here
       try {
           PrintWriter writer=new PrintWriter(new File(filename));
           for(int i=0;i<parsedFile.length;i++)
           {
               if(parsedFile[i].contains("LOG"))
                   writer.write(parsedFile[i]+"\n");
           }
           writer.close();

       } catch (FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }

   }


   public static void main(String[] args) {

//Provide file path accordingly

       String [] array=readFile("C:\\Users\\asus\\InputText.txt");
       String[] parsedArray= {"LOG username: happy_cat31","password: MrMuffins1234","LOG username: sad_panda","password: BambooLover83"};

//Provide file path accordingly
       reverseFile(array,"C:\\Users\\asus\\OutputText.txt");

//Provide file path accordingly
       logFile(parsedArray, "C:\\Users\\asus\\OutputLog.txt");

   }

}

Output:

InputFile:

Reverse Output:

LogOutput:


**************Please do upvote to appreciate our time. Thank you!******************


Related Solutions

Create a class DogWalker member List <String>doggies method: void addDog(String name ) //add dog to the...
Create a class DogWalker member List <String>doggies method: void addDog(String name ) //add dog to the List method: void printDogList() //print all dogs in list /* You’ll need an index. Iterate over your list of dog names in a while loop. Use your index to “get” the dog at the current index When you ‘find’ your dog name in the list, print it out */ Method: void findDogUsingWhile(String dogName) /* You’ll need an index. Iterate over your list of dog...
protected String name;                                      &nbsp
protected String name;                                                                                                           protected ArrayList<Stock> stocks;     protected double balance;                                                                              + Account ( String name, double balance) //stocks = new ArrayList<Stock>() ; + get and set property for name; get method for balance + void buyStock(String symbol, int shares, double unitPrice ) //update corresponding balance and stocks ( stocks.add(new Stock(…..)); ) + deposit(double amount) : double //returns new balance                                                                 + withdraw(double amount) : double //returns new balance + toString() : String                                                                  @Override     public String toString(){         StringBuffer str =...
PLEASE USE MEHODES (Print part of the string) Write a method with the following header that...
PLEASE USE MEHODES (Print part of the string) Write a method with the following header that returns a partial string: public static String getPartOfString(int n, String firstOrLast, String inWord) Write a test program that uses this method to display the first or last number of characters of a string provided by the user. The program should output an error if the number requested is larger than the string. SAMPLE RUN #1: java PartOfString Enter a string: abracadabra↵ Enter the number...
Use python. redact_file: This function takes a string filename. It writes a new file that has...
Use python. redact_file: This function takes a string filename. It writes a new file that has the same contents as the argument, except that all of the phone numbers are redacted. Assume that the filename has only one period in it. The new filename is the same as the original with '_redacted' added before the period. For instance, if the input filename were 'myfile.txt', the output filename would be 'myfile_redacted.txt'. Make sure you close your output file.
In Java, Here is a basic Name class. class Name { private String first; private String...
In Java, Here is a basic Name class. class Name { private String first; private String last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Name other) { return this.first.equals(other.first) && this.last.equals(other.last); } } Assume we have a program (in another file) that uses this class. As part of the program, we need to write a method with the following header: public static boolean exists(Name[] names, int numNames, Name name) The goal of...
Define a function file_to_hist() which takes a string representing a filename, opens the file, reads its...
Define a function file_to_hist() which takes a string representing a filename, opens the file, reads its contents, closes the file,* and returns a histogram based on the letter frequencies in the given file. If no such file exists, your function should return an empty histogram (i.e., an empty dictionary {}). So for example, if the file nash.txt was in the same directory as char_hist3.py and had the following contents: I have never seen a purple cow, And I never hope...
Language: Python 3 Compose a function process which accepts a string filename. process should return a...
Language: Python 3 Compose a function process which accepts a string filename. process should return a list of records contained in the file. #define your function here # Create a blank list called `entries` and an empty string called `current_style`. # Open the file `filename`, read the data using readlines(), and close it. # Loop through each line of the file and do the following: # Strip the whitespace off of the ends of the line using the `strip` method....
program c Write a program called filesearch that accepts two command-line arguments: A string A filename...
program c Write a program called filesearch that accepts two command-line arguments: A string A filename If the user did not supply both arguments, the program should display an error message and exit. The program opens the given filename. Each line that contains the given string is displayed. Use the strstr function to search each line for the string. You may assume no line is longer than 255 characters. The matching lines are displayed to standard output (normally the screen).
Write a method that concatenates two strings passed as parameters.    Version #1 - assign to...
Write a method that concatenates two strings passed as parameters.    Version #1 - assign to the 1st parameter the concatenation of both parameters. Perform the concatenation using the + operator. We are assuming reference parameter work that way (they don't).    Version #2 - fine. return the value of the 1st param after concatenating to it the second parameter then.    Version #3 - Let's do it the proper way now, I say. Create a temporary String reference variable...
Following is hw14. Save the demo filename as lastname_hw14.java and the class name as lastname_people.java. Following...
Following is hw14. Save the demo filename as lastname_hw14.java and the class name as lastname_people.java. Following are three arrays each containing 50 values. Store all three arrays in the main method. Write an object to transfer the three arrays. int []age[] = {70, 68, 52, 69, 40, 59, 61, 34, 45, 50, 43, 22, 35, 50, 67, 33, 36, 22, 63, 65, 56, 31, 55, 28, 30, 24, 55, 35, 39, 59, 68, 50, 33, 45, 26, 54, 44, 56,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT