0

Here is the modified code, when i run the program it works,but it doesn't work as i expected. I don't know why it won't write the lines that i typed after typing "add", and also it didn't show anything when i typed "show". Seems like i might missing something :

import java.io.BufferedReader; 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.List;

public class unfinished {

public static void main(String[] args) throws IOException {

    //String command;
    //int index = 0;

    Path path = FileSystems.getDefault().getPath("source.txt");
    List<String> list = loadList(path);

    try(Scanner sc = new Scanner(System.in)){
    //  System.out.print("Enter the Command: ");
       String[] input = sc.nextLine().split(" ");
       while(input.length > 0 && !input[0].equals("exit")){ 

           switch(input[0]){
           case "add" : addToList(input, list); break;
           case "remove" : removeFromList(input, list); break;
           case "show": showList(input, list); break;
        }
          }
          input = sc.nextLine().split(" ");

}

    saveList(path, list);

}

here is the part of my old code for sorting and clear:

/** 
Collections.sort(MenuArray);
int i = 0;
for (String temporary : MenuArray) {
System.out.println(++i + ". " + temporary);
}
//clear
MenuArray.clear();
System.out.println("All objects have been cleared !");
*/

private static void saveList(Path path, List<String> list) throws IOException {
    // TODO Auto-generated method stub
           Files.write(path, list, Charset.defaultCharset(), 
              StandardOpenOption.CREATE, 
              StandardOpenOption.TRUNCATE_EXISTING);
        }


private static void removeFromList(String[] input, List<String> list) {
// TODO Auto-generated method stub

}


private static void showList(String[] input, List<String> list) {
    // TODO Auto-generated method stub

}

private static void addToList(String[] input, List<String> list) {
    // TODO Auto-generated method stub

}

private static List<String> loadList(Path path)  throws IOException {
    // TODO Auto-generated method stub
           return Files.readAllLines(path, Charset.defaultCharset());
}


}
lawZ
  • 39
  • 1
  • 3
  • 9

3 Answers3

2

By one hand, you could simplify thing by writing your program as an actual menu program by using switch statements. For instance:

Path path = FileSystems.getDefault().getPath("jedis.txt");
List<String> list = loadList(path);

try(Scanner sc = new Scanner(System.in)){
   String[] input = sc.nextLine().split(" ");
   while(input.length > 0 && !input[0].equals("exit")){
      switch(input[0]){
         case "add" : addToList(input, list); break;
         case "show": showList(input, list); break;
      }
      input = sc.nextLine().split(" ");
   }
}

saveList(path, list);

Notice the importance of using a try statement around the scanner, since the scanner consumes a resource (System.in) it is important to free that resource when you no longer need it.

Now, I have separated the logic of the actions from the rendering of the menu. This way the menu algorithm can worry only about that, whereas every action methods can worry about its own action. So, you can worry about reading the file in loadList, and worry about saving it in saveList, worry about adding a new element to the list in addToList, and so on

Now, if the file in question simply contains strings, as your questions seem to imply. You could do something really simple to read it using Java NIO, like

public static List<String> loadList(Path path) throws IOException {
   return Files.readAllLines(path, Charset.defaultCharset());
}

And writing the file back would be as simple as:

public static void saveList(Path path, List<String> list) throws IOException {
   Files.write(path, list, Charset.defaultCharset(), 
      StandardOpenOption.CREATE, 
      StandardOpenOption.TRUNCATE_EXISTING);
}

Or you can use the traditional Java I/O classes like BufferedReader and FileWriter as other answer seems to suggest.

-- EDIT 1--

Well, if you wanted to remove an element from the list, all you have to do is to support another operation in the menu:

switch(input[0]){
   case "add" : addToList(input, list); break;
   case "remove" : removeFromList(input, list); break;
   case "show": showList(input, list); break;
}

And implement the corresponding action method. For instance, for that remove action, it could be something like this:

public static void removeFromList(String[] input, List<String> list){
  if(input.length == 2 && input[1].matches("\\d+")){
      int index = Integer.parseInt(input[1]);
      if(index < list.size()){
         list.remove(index);
      } else {
         System.out.println("Invalid index: " + index);
      }
   } else {
      System.out.println("Invalid input: " + Arrays.toString(input));
   }
}

In this case the user would need to input a command like "remove 10" to remove that index from the list.

You may want to implement your method to show the list in a such way that it displays the indices of the elements, so that the user can more easily choose which to remove. For example, the show list method should display something like

0. Obi-wan
1. Yodah
2. Luke
3. Anakin

-- EDIT 2--

In order to read the user input you may want to display a message like: "Enter command (or type help for options): ".

Evidently, you'd have to put this just before you read the user's input with sn.nextLine(). Since we are doing this in two different places, you'd probably prefer to write a method for this, so that you write this code only once. Somewhat like:

private String[] getComnand(Scanner sc) {
   System.out.println("Enter command (or type help for options): ");
   return sc.nextLine().split(" ");
}

And now we can reuse this in the menu code.

Also, you may want to fix the menu to display the list of commands available for the user whenever he types a wrong command or when s/he types help.

switch(input[0]){
   case "add" : addToList(input, list); break;
   case "remove" : removeFromList(input, list); break;
   case "show": showList(input, list); break;
   default: showHelp(input);
}

In the showHelp() method you'd probably want to display the list of available commands. Somewhat like:

Available commands:

add <name>...........Adds the given name to the list
remove <index>.......Removes the item in the given index
show.................Displays all items and their indices
help.................Displays this help
Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
  • Yeah, this is truly helpful,tq Sir!! Then, what about if I want to delete a specific object by the index of the string? For example, there are 10 objects in the txt, and i want to delete the 7th object with the following command : Delete 7 . – lawZ Sep 28 '13 at 13:37
  • Wow, it's really useful !! actually there're still some method about sorting the objects by alphabetical order and clear all of the objects that exist. My program already finished, but I want to implemented the ".txt" things, that's why I should rewriting and fixing so many parts of it.I just want to try it by my own self, and if I get stuck I'm gonna ask you again,Sir ! tq very much ! – lawZ Sep 28 '13 at 14:30
  • @lawZ Well, the sorting can be easily done using ```Collections.sort``` method. You simply pass the list and it will sort it for you. And the clearing of the list can be done by invoking the ```clear``` method on the list itself. So, I reckon you are close to finishing. – Edwin Dalorzo Sep 28 '13 at 14:40
  • I just edited the code on my quest, but where should i put the println("Enter the command:"), and could you please make it clear the way the program running? 'cause i kinda don't understand it. It won't write/read/show when i tested it. Also i already added the other methods too. – lawZ Sep 29 '13 at 05:08
  • @lawZ I edited the answer again to address your questions. – Edwin Dalorzo Sep 29 '13 at 13:27
  • on the addList method, how can i implement it? – lawZ Oct 24 '13 at 08:55
0

At the beginning of the program , you reconstruct the array list from the file, if it exists. Then do all the operation you want, finally if the command is exit, write the contents to the file and exit

upog
  • 4,965
  • 8
  • 42
  • 81
0
package com.morgan.stanley;

import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner;

public class unfinished {

public static void main(String[] args) {

    String command;
    int index = 0;

    Scanner input = new Scanner(System.in);
    ArrayList<String> MenuArray = new ArrayList<String>();

    boolean out = false;

    while (!out) {
        System.out.print("Enter the Command: ");

        command = input.nextLine();
        if (command.startsWith("add ")) {
            MenuArray.add(command.substring(4));
            index++;

            try {
                FileOutputStream fos = new FileOutputStream(new File("output.txt"));
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(MenuArray); // write MenuArray to
                                            // ObjectOutputStream
                oos.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

        else if (command.startsWith("show")) {
            int i = 0;

            for (String temporary : MenuArray) {
                System.out.println(++i + ". " + temporary);
            }
             showContents("output.txt");

        }

        else if (command.startsWith("exit")) {
            out = true;
        }

        else {
            System.out.println("Wrong Command !");
        }
    }

    System.out.println("Done ! Exit");

}

private static String readFile(BufferedReader reader) {
    // TODO Auto-generated method stub
    return null;
}

private static void showContents(String string) {
    try {
        List<String> results = new ArrayList<String>();
        FileInputStream fis = new FileInputStream(new File("output.txt"));
        ObjectInputStream ois = new ObjectInputStream(fis);
        results = (ArrayList)ois.readObject();
        System.out.println(results);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

}

} /* Enter the Command: add Pratik Enter the Command: show 1. Pratik [Pratik] Enter the Command: */

Your code for witing to the text file is correct and works as expected. When user enters show use the above function to deserialize the object from the txt file and display it

Pratik Shelar
  • 3,154
  • 7
  • 31
  • 51