Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在.txt文件中放置、读取和修改ArrayList对象?_Java_Arrays_Methods_Arraylist - Fatal编程技术网

Java 如何在.txt文件中放置、读取和修改ArrayList对象?

Java 如何在.txt文件中放置、读取和修改ArrayList对象?,java,arrays,methods,arraylist,Java,Arrays,Methods,Arraylist,这是修改后的代码, 当我运行这个程序时,它可以工作,但是它没有像我预期的那样工作。我不知道为什么它不会写我在键入“add”后键入的行,而且在键入“show”时它也没有显示任何内容。似乎我遗漏了什么: import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; impo

这是修改后的代码, 当我运行这个程序时,它可以工作,但是它没有像我预期的那样工作。我不知道为什么它不会写我在键入“add”后键入的行,而且在键入“show”时它也没有显示任何内容。似乎我遗漏了什么:

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

}
导入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;
公共课未完成{
公共静态void main(字符串[]args)引发IOException{
//字符串命令;
//int指数=0;
Path Path=FileSystems.getDefault().getPath(“source.txt”);
列表=加载列表(路径);
try(Scanner sc=新扫描仪(System.in)){
//System.out.print(“输入命令:”);
字符串[]输入=sc.nextLine().split(“”);
而(input.length>0&&!input[0].equals(“exit”){
开关(输入[0]){
案例“添加”:添加列表(输入,列表);中断;
案例“移除”:从列表中移除(输入,列表);中断;
案例“显示”:显示列表(输入,列表);中断;
}
}
输入=sc.nextLine().split(“”);
}
保存列表(路径、列表);
}
以下是我的旧代码中用于排序和清除的部分:

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


}
/**
Collections.sort(MenuArray);
int i=0;
for(字符串临时:MenuArray){
System.out.println(++i+“+”临时);
}
//清楚的
MenuArray.clear();
System.out.println(“所有对象都已清除!”);
*/
私有静态void存储列表(路径,列表列表)引发IOException{
//TODO自动生成的方法存根
Files.write(路径、列表、字符集.defaultCharset(),
StandardOpenOption.CREATE,
StandardOpenOption。截断_(现有);
}
私有静态void removeFromList(字符串[]输入,列表){
//TODO自动生成的方法存根
}
私有静态void showList(字符串[]输入,列表){
//TODO自动生成的方法存根
}
私有静态void addToList(字符串[]输入,列表){
//TODO自动生成的方法存根
}
私有静态列表loadList(路径路径)引发IOException{
//TODO自动生成的方法存根
返回Files.readAllLines(路径,Charset.defaultCharset());
}
}

在程序开始时,您可以从文件中重建数组列表(如果存在)。然后执行所有需要的操作,最后,如果命令是exit,则将内容写入文件并退出

package com.morgan.stanley;
导入java.io.BufferedReader; 导入java.io.File; 导入java.io.FileInputStream; 导入java.io.FileNotFoundException; 导入java.io.FileOutputStream; 导入java.io.IOException; 导入java.io.ObjectInputStream; 导入java.io.ObjectOutputStream; 导入java.util.ArrayList; 导入java.util.List; 导入java.util.Scanner

公共课未完成{

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

}
publicstaticvoidmain(字符串[]args){
字符串命令;
int指数=0;
扫描仪输入=新扫描仪(System.in);
ArrayList MenuArray=新建ArrayList();
布尔输出=假;
当(!外出){
System.out.print(“输入命令:”);
command=input.nextLine();
if(command.startsWith(“add”)){
MenuArray.add(command.substring(4));
索引++;
试一试{
FileOutputStream fos=新的FileOutputStream(新文件(“output.txt”);
ObjectOutputStream oos=新的ObjectOutputStream(fos);
oos.writeObject(MenuArray);//将MenuArray写入
//ObjectOutputStream
oos.close();
}捕获(例外情况除外){
例如printStackTrace();
}
}
else if(command.startsWith(“show”)){
int i=0;
for(字符串临时:MenuArray){
System.out.println(++i+“+”临时);
}
showContents(“output.txt”);
}
else if(command.startsWith(“exit”)){
out=真;
}
否则{
System.out.println(“错误的命令!”);
}
}
System.out.println(“完成!退出”);
}
私有静态字符串读取文件(BufferedReader读取器){
//TODO自动生成的方法存根
返回null;
}
私有静态void showContents(字符串){
试一试{
列表结果=新建ArrayList();
FileInputStream fis=新的FileInputStream(新文件(“output.txt”);
ObjectInputStream ois=新ObjectInputStream(fis);
结果=(ArrayList)ois.readObject();
系统输出打印项次(结果);
}捕获(例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
} 
}
} /*输入命令:addpratik 输入命令:show 1.普拉蒂克 [普拉蒂克] 输入命令: */


您的文本文件代码是正确的,并按预期工作。当用户输入show时,使用上述函数从txt文件中反序列化对象并用一只手显示它,您可以通过使用switch语句将程序编写为实际的菜单程序来简化操作。例如:

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);
将文件写回将非常简单:

public static void saveList(Path path, List<String> list) throws IOException {
   Files.write(path, list, Charset.defaultCharset(), 
      StandardOpenOption.CREATE, 
      StandardOpenOption.TRUNCATE_EXISTING);
}
并实现相应的动作方法。例如,对于该移除操作,可以是这样的:

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

为了读取用户输入,您可能需要显示如下消息:“输入命令(或键入选项帮助):”

显然,在您使用
sn.nextLine()
读取用户输入之前,您必须先输入这些内容。因为我们在两个不同的地方做这件事,所以您可能更愿意为
switch(input[0]){
   case "add" : addToList(input, list); break;
   case "remove" : removeFromList(input, list); break;
   case "show": showList(input, list); break;
}
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));
   }
}
0. Obi-wan
1. Yodah
2. Luke
3. Anakin
private String[] getComnand(Scanner sc) {
   System.out.println("Enter command (or type help for options): ");
   return sc.nextLine().split(" ");
}
switch(input[0]){
   case "add" : addToList(input, list); break;
   case "remove" : removeFromList(input, list); break;
   case "show": showList(input, list); break;
   default: showHelp(input);
}
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