1

Background: This program reads in a text file and replaces a word in the file with user input.

Problem: I am trying to read in a line of text from a text file and store the words into an array.

Right now the array size is hard-coded with an number of indexes for test purposes, but I want to make the array capable of reading in a text file of any size instead.

Here is my code.

public class FTR {

public static Scanner input = new Scanner(System.in);
public static Scanner input2 = new Scanner(System.in);
public static String fileName = "C:\\Users\\...";
public static String userInput, userInput2;
public static StringTokenizer line;
public static String array_of_words[] = new String[19]; //hard-coded

/* main */
public static void main(String[] args) {
    readFile(fileName);
    wordSearch(fileName);
    replace(fileName);

}//main

/*
 * method: readFile
 */
public static void readFile(String fileName) {
    try {
        FileReader file = new FileReader(fileName);
        BufferedReader read = new BufferedReader(file);

        String line_of_text = read.readLine();
        while (line_of_text != null) {
            System.out.println(line_of_text);
            line_of_text = read.readLine();
        }
    } catch (Exception e) {
        System.out.println("Unable to read file: " + fileName);
        System.exit(0);
    }
    System.out.println("**************************************************");
}

/*
* method: wordSearch
*/
public static void wordSearch(String fileName) {
    int amount = 0;
    System.out.println("What word do you want to find?");
    userInput = input.nextLine();
    try {
        FileReader file = new FileReader(fileName);
        BufferedReader read = new BufferedReader(file);

        String line_of_text = read.readLine();
        while (line_of_text != null) { //there is a line to read
            System.out.println(line_of_text);
            line = new StringTokenizer(line_of_text); //tokenize the line into words
            while (line.hasMoreTokens()) { //check if line has more words
                String word = line.nextToken(); //get the word 
                if (userInput.equalsIgnoreCase(word)) {
                    amount += 1; //count the word
                }
            }
            line_of_text = read.readLine(); //read the next line
        }
    } catch (Exception e) {
        System.out.println("Unable to read file: " + fileName);
        System.exit(0);
    }
    if (amount == 0) { //if userInput was not found in the file
        System.out.println("'" + userInput + "'" + " was not found.");
        System.exit(0);
    }
    System.out.println("Search for word: " + userInput);
    System.out.println("Found: " + amount);
}//wordSearch

/*
* method: replace
*/
public static void replace(String fileName) {
    int amount = 0;
    int i = 0;
    System.out.println("What word do you want to replace?");
    userInput2 = input2.nextLine();
    System.out.println("Replace all " + "'" + userInput2 + "'" + " with " + "'" + userInput + "'");
    try {
        FileReader file = new FileReader(fileName);
        BufferedReader read = new BufferedReader(file);

        String line_of_text = read.readLine();
        while (line_of_text != null) { //there is a line to read
            line = new StringTokenizer(line_of_text); //tokenize the line into words
            while (line.hasMoreTokens()) { //check if line has more words
                String word = line.nextToken(); //get the word 
                if (userInput2.equalsIgnoreCase(word)) {
                    amount += 1; //count the word
                    word = userInput;
                }
                array_of_words[i] = word; //add word to index in array   
                System.out.println("WORD: " + word + " was stored in array[" + i + "]");
                i++; //increment array index     
            }
  //THIS IS WHERE THE PRINTING HAPPENS
            System.out.println("ARRAY ELEMENTS: " + Arrays.toString(array_of_words));
            line_of_text = read.readLine(); //read the next line
        }
        BufferedWriter outputWriter = null;
        outputWriter = new BufferedWriter(new FileWriter("C:\\Users\\..."));
        for (i = 0; i < array_of_words.length; i++) { //go through the array
            outputWriter.write(array_of_words[i] + " "); //write word from array to file
        }
        outputWriter.flush();
        outputWriter.close();
    } catch (Exception e) {
        System.out.println("Unable to read file: " + fileName);
        System.exit(0);
    }
    if (amount == 0) { //if userInput was not found in the file
        System.out.println("'" + userInput2 + "'" + " was not found.");
        System.exit(0);
    }
}//replace
}//FTR

3 Answers3

2

You can use java.util.ArrayList (which dynamically grows unlike an array with fixed size) to store the string objects (test file lines) by replacing your array with the below code:

public static List<String> array_of_words = new java.util.ArrayList<>();

You need to use add(string) to add a line (string) and get(index) to retrieve the line (string)

Please refer the below link for more details: http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

Vasu
  • 21,832
  • 11
  • 51
  • 67
2

You may want to give a try to ArrayList.

In Java normal arrays cannot be initialized without giving initial size and they cannot be expanded during run time. Whereas ArrayLists have resizable-array implementation of the List interface.ArrayList also comes with number of useful builtin functions such as

Size()

isEmpty()

contains()

clone()

and others. On top of these you can always convert your ArrayList to simple array using ArrayList function toArray(). Hope this answers your question. I'll prepare some code and share with you to further explain things you can achieve using List interface.

BountyHunter
  • 89
  • 2
  • 10
0

Use not native [] arrays but any kind of java collections

List<String> fileContent = Files.readAllLines(Paths.get(fileName));
fileContent.stream().forEach(System.out::println);

long amount = fileContent.stream()
    .flatMap(line -> Arrays.stream(line.split(" +")))
    .filter(word -> word.equalsIgnoreCase(userInput))
    .count();

List<String> words = fileContent.stream()
    .flatMap(line -> Arrays.stream(line.split(" +")))
    .filter(word -> word.length() > 0)
    .map(word -> word.equalsIgnoreCase(userInput) ? userInput2 : word)
    .collect(Collectors.toList());

Files.write(Paths.get(fileName), String.join(" ", words).getBytes());

of course you can works with such lists more traditionally, with loops

for(String line: fileContent) {
    ...
}

or even

for (int i = 0; i < fileContent.size(); ++i) {
    String line = fileContent.get(i);
    ...
}

i just like streams :)

rustot
  • 331
  • 1
  • 11