繁体   English   中英

如何添加从文件读取的字符串到ArrayList?

[英]how to add string read from file to an ArrayList?

我有一个超级初学者的问题。 我今天有一个计算机科学测试,实践问题之一是:

  • 编写执行以下任务的程序:
  • 打开一个名为hello.txt的文件。
  • 将消息“ Hello,World!”存储在文件中。
  • 关闭文件。
  • 再次打开相同的文件。
  • 将消息读入字符串变量并打印。

到目前为止,这是我拥有的代码:

import java.util.*;
import java.io.*;

public class ReadFile
{
    public static void main(String[] args) throws FileNotFoundException
    {
        PrintWriter out = new PrintWriter("hello.txt");
        out.println("Hello, World");
        File readFile = new File("hello.txt");
        Scanner in = new Scanner(readFile);
        ArrayList<String> x = new ArrayList<String>();
        int y = 0;

        while (in.hasNext())
        {
            x.add(in.next());
            y++;
        }

        if (x.size() == 0)
        {
            System.out.println("Empty.");
        }
        else
        {
            System.out.println(x.get(y));
        }

        in.close();
        out.close();     
    }
}

此代码有什么问题?

1)您需要关闭流

2)您需要使用(y-1)引用x Arraylist,否则将获得java.lang.IndexOutOfBoundsException 索引从0开始而不是从1开始。

http://www.tutorialspoint.com/java/util/arraylist_get.htm

   public static void main(String[] args) throws FileNotFoundException
        {
            PrintWriter out = new PrintWriter("hello.txt");
            out.println("Hello, World");
            out.close();
            File readFile = new File("hello.txt");
            Scanner in = new Scanner(readFile);
            ArrayList<String> x = new ArrayList<String>();
            int y = 0;

            while (in.hasNext())
            {
                x.add(in.next());
                y++;
            }

            in.close();  

            if (x.size() == 0)
            {
                System.out.println("Empty.");
            }
            else
            {
                System.out.println(x.get(y-1));
            }

        }
    }

我猜你不能从文件中读取任何东西的代码师出了什么问题。

这是因为PrintWriter已缓冲

fileName-用作此编写器目标的文件名。 如果文件存在,那么它将被截断为零大小; 否则,将创建一个新文件。 输出将被写入文件并被缓冲

您需要先关闭刚刚写入的文件,然后再打开文件以进行读取,以便将更改保存到物理存储中。 因此移出out.close(); 就在out.println("Hello, World");

class FileWritingDemo {
public static void main(String [] args) {
char[] in = new char[13]; // to store input
int size = 0;
try {
File file = new File("MyFile.txt"); // just an object

FileWriter fw = new FileWriter(file); // create an actual file & a FileWriter obj
fw.write("Hello, World!"); // write characters to the file
fw.flush(); // flush before closing
fw.close(); // close file when done

FileReader fr = new FileReader(file); // create a FileReader object
size = fr.read(in); // read the whole file!
for(char c : in) // print the array
System.out.print(c);
fr.close(); // again, always close
} catch(IOException e) { }
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM