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

(java) Part 1 Write a method named compare that accepts two String arrays as parameters and...
(java) Part 1 Write a method named compare that accepts two String arrays as parameters and returns a boolean. The method should return true if both arrays contain the same values (case sensitive), otherwise returns false. Note - the two arrays must be the same length and the values must be in the same order to return true. Part  2 Write a method named generateArray that accepts an int size as its parameter and returns an int[] array where each element...
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...
PYTHON. Create a function that accepts a filename where in each line there is a name...
PYTHON. Create a function that accepts a filename where in each line there is a name of a type of bird. use a python dictionary in order to count the # of time each bird appears. (1 line = 1 appearance) Loop over your dict. to print each species and the # of times it was seen in the file once all lines have been counted. return dictionary containing count the filename opens this: blackbird canary hummingbird canary hummingbird canary...
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.
Using JES/ Jython Function Name: decoder() Parameters: message1-string containing first part of secret message message2-string containing...
Using JES/ Jython Function Name: decoder() Parameters: message1-string containing first part of secret message message2-string containing second part of secret message Write a function that decodes them by retrieving every other character from both encrypted messages. Test Cases: >>>decoder("Rsupnk","oFpansot") Run Fast >>>decoder("Fkrneoem ktthpes","eAvleiselnos") Free the Aliens
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...
C++ Only Create a function named PrintStudents, which takes a string input filename and an integer...
C++ Only Create a function named PrintStudents, which takes a string input filename and an integer minimum score value and a string output file name as a parameters. The function will read the student scores and names from the file and output the names of the students with scores greater than or equal to the value given. This function returns the integer number of entries read from the file. If the input file cannot be opened, return -1 and do...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT