如何在 .txt 文件中放置、读取和修改我的 ArrayList 对象? [英] How can I put,read,and modified my ArrayList Objects on a .txt file?

查看:52
本文介绍了如何在 .txt 文件中放置、读取和修改我的 ArrayList 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是修改后的代码,当我运行程序时,它可以工作,但没有按我预期的那样工作.我不知道为什么它不会写出我在输入add"后输入的行,而且当我输入show"时它也没有显示任何内容.好像我可能遗漏了什么:

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());
}


}

推荐答案

一方面,您可以通过使用 switch 语句将程序编写为实际菜单程序来简化事情.例如:

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);

请注意在扫描器周围使用 try 语句的重要性,因为扫描器消耗资源 (System.in),因此在您不再需要该资源时释放该资源很重要.

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.

现在,我已经将操作的逻辑与菜单的呈现分开了.这样菜单算法可以只关心那个,而每个动作方法可以关心它自己的动作.所以,你可以担心在loadList中读取文件,担心在saveList中保存它,担心在addToList中添加一个新元素到列表中代码>等

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

现在,如果有问题的文件只包含字符串,正如您的问题所暗示的那样.你可以用 Java NIO 做一些非常简单的事情来阅读它,比如

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);
}

或者您可以使用传统的 Java I/O 类,如 BufferedReader 和 FileWriter,因为其他答案似乎暗示了这一点.

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

-- 编辑 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;
}

并实现相应的action方法.例如,对于那个删除操作,它可能是这样的:

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));
   }
}

在这种情况下,用户需要输入remove 10"之类的命令才能从列表中删除该索引.

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

您可能希望实现您的方法以显示元素索引的方式显示列表,以便用户可以更轻松地选择要删除的内容.例如,show 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

-- 编辑 2--

为了读取用户输入,您可能希望显示如下消息:输入命令(或键入帮助以获取选项):".

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

显然,您必须在使用 sn.nextLine() 读取用户输入之前将其放入.由于我们在两个不同的地方执行此操作,您可能更愿意为此编写一个方法,以便您只编写一次此代码.有点像:

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);
}

showHelp() 方法中,您可能希望显示可用命令的列表.有点像:

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

这篇关于如何在 .txt 文件中放置、读取和修改我的 ArrayList 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆