我怎么能放,读取和修改的.txt文件的ArrayList我的对象? [英] How can I put,read,and modified my ArrayList Objects on a .txt file?

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

问题描述

下面是修改code,
当我运行程序它的工作原理,但我希望这是行不通的。我不知道为什么它不会写我输入加后输入线,并且也没有显示任何东西,当我输入秀。好像我可能失去了一些东西:

 进口java.io.BufferedReader中;
进口的java.io.File;
进口java.io.FileInputStream中;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口java.io.ObjectInputStream中;
进口java.io.ObjectOutputStream中;
进口java.nio.charset.Charset中;
进口java.nio.file.FileSystems;
进口java.nio.file.Files;
进口java.nio.file.Path;
进口java.nio.file.StandardOpenOption;
进口的java.util.ArrayList;
进口java.util.Collections中;
进口java.util.Scanner中;
进口的java.util.List;公共类未完成{公共静态无效的主要(字串[] args)抛出IOException    //字符串命令;
    // INT索引= 0;    路径path = FileSystems.getDefault()的getPath(的Source.txt);
    清单<串GT;清单= loadList(路径);    尝试(扫描仪SC =新的扫描仪(System.in)){
    // System.out.print(输入命令:);
       的String []输入= sc.nextLine()分裂()。
       而(input.length大于0和放大器;&放大器;!输入[0] .equals(退出)){           开关(输入[0]){
           情况下的添加:addToList(输入,清单);打破;
           案删除:removeFromList(输入,清单);打破;
           案秀:showList(输入,清单);打破;
        }
          }
          输入= sc.nextLine()分裂()。}    saveList(路径表);}

这里是我的老code的分类和明确的部分:

  / **
Collections.sort(MenuArray);
INT I = 0;
对于(临时字符串:MenuArray){
的System.out.println(++ I + +临时的。);
}
//明确
MenuArray.clear();
的System.out.println(所有物品已被清除!);
* /私有静态无效saveList(路径路径列表<串GT;清单)抛出IOException
    // TODO自动生成方法存根
           Files.write(路径,列表Charset.defaultCharset()
              StandardOpenOption.CREATE,
              StandardOpenOption.TRUNCATE_EXISTING);
        }
私有静态无效removeFromList(字符串[]输入列表与LT;弦乐>名单){
// TODO自动生成方法存根}
私有静态无效showList(字符串[]输入列表与LT;弦乐>名单){
    // TODO自动生成方法存根}私有静态无效addToList(字符串[]输入列表与LT;弦乐>名单){
    // TODO自动生成方法存根}私人静态列表<串GT; loadList(路径路径)抛出IOException
    // TODO自动生成方法存根
           返回Files.readAllLines(路径,Charset.defaultCharset());
}
}


解决方案

这是一方面​​,你可以通过编写程序通过使用switch语句实际的菜单程序简化的事情。例如:

 路径path = FileSystems.getDefault()的getPath(jedis.txt);
清单<串GT;清单= loadList(路径);尝试(扫描仪SC =新的扫描仪(System.in)){
   的String []输入= sc.nextLine()分裂()。
   而(input.length大于0和放大器;&放大器;!输入[0] .equals(退出)){
      开关(输入[0]){
         情况下的添加:addToList(输入,清单);打破;
         案秀:showList(输入,清单);打破;
      }
      输入= sc.nextLine()分裂()。
   }
}saveList(路径表);

注意使用扫描仪周围try语句的重要性,因为扫描仪需要消耗资源(System.in)它来释放资源,当你不再需要它是非常重要的。

现在,我已经从菜单的呈现分离的动作的逻辑。通过这种方式,菜单算法可以只担心有关,而每一个动作方法可以不用担心自己的行动。所以,你可以不用担心读取文件中的 loadList ,并担心其保存在 saveList ,担心加入新元素添加到列表中的 addToList

现在,如果有问题的文件只包含字符串,如您的问题似乎暗示。你可以做一些非常简单的使用Java NIO读它,像

 公共静态列表<串GT; loadList(路径路径)抛出IOException
   返回Files.readAllLines(路径,Charset.defaultCharset());
}

和写回文件是这么简单:

 公共静态无效saveList(路径路径列表<串GT;清单)抛出IOException
   Files.write(路径,列表Charset.defaultCharset()
      StandardOpenOption.CREATE,
      StandardOpenOption.TRUNCATE_EXISTING);
}

或作为其他的答案似乎在暗示你可以使用传统的Java I / O类象的BufferedReader和FileWriter的。

- 编辑1 -

好吧,如果你想从列表中删除元素,你所要做的就是支持菜单中的另一种操作:

 开关(输入[0]){
   情况下的添加:addToList(输入,清单);打破;
   案删除:removeFromList(输入,清单);打破;
   案秀:showList(输入,清单);打破;
}

和执行相应的操作方法。例如,对于删除操作,也可能是这样的:

 公共静态无效removeFromList(字符串[]输入列表与LT;弦乐>名单){
  如果(input.length == 2和;&放大器;输入[1] .matches(\\\\ D +)){
      INT指数=的Integer.parseInt(输入[1]);
      如果(指数<则为list.size()){
         list.remove(索引);
      }其他{
         的System.out.println(无效的索引:+指数);
      }
   }其他{
      的System.out.println(无效的输入:+ Arrays.toString(输入));
   }
}

在这种情况下,用户需要输入诸如去除10的命令从列表中删除索引。

您可能要实现你的方法,以显示它显示的元素的索引,使用户可以更容易地选择哪些删除这样的方式列表。例如,节目列表的方法应该显示类似

  0。欧比旺
1. Yodah
卢克
3.阿纳金

- 编辑2 -

为了读取用户输入您可能想显示一条消息,如:输入命令(或选择键入help):

显然,你必须把这个你读了用户与输入sn.nextLine之前()。由于我们是在两个不同的地方这样做,你可能preFER为此编写一个方法,让你写这code只有一次。有点像:

 私有String [] getComnand(扫描仪SC){
   的System.out.println(输入命令(或选择键入help):);
   返回sc.nextLine()分裂()。
}

现在,我们可以在菜单code重用这个。

此外,您可能要修复的菜单中显示的命令可用于用户列表,每当他一个类型错误的命令,或当他/她帮类型

 开关(输入[0]){
   情况下的添加:addToList(输入,清单);打破;
   案删除:removeFromList(输入,清单);打破;
   案秀:showList(输入,清单);打破;
   默认:showHelp(输入);
}

showHelp你可能会想显示可用的命令列表()方法。有点像:

 可用的命令:添加<名称> ...........增加给定名称的列表
删除<索引> .......删除在给定指标的项目
显示.................显示所有项目及其指数
帮助.................显示此帮助

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


}

解决方案

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

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

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