使用Java arraylist存储来自文件的扫描数据

时间:2016-04-16 20:47:06

标签: java

我是java新手,但不是编码。我试图找出java,因为它是我这个学期的课程的一部分,我在抓住它的想法和在java中实现的东西时遇到了一个非常难的问题。

我的问题是我不确定我是否正确使用arraylist从文件扫描中获取数据并将其输入到arraylist中以便稍后进行排序和打印。我只是遇到了解决java的问题,因为我是java新手,所以任何帮助都会很棒。

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
    private static  ArrayList<String> list = new ArrayList<String>();
    // returns an InputStream that gets data from the named file
    private static InputStream getFileInputStream(String fileName) throws Exception {
        InputStream inputStream;
        try {
            inputStream = new FileInputStream(new File(fileName));
        }
        catch (FileNotFoundException e) {       // no file with this name exists
            inputStream = null;
            throw new Exception("unable to open the file -- " + e.getMessage());
        }
        return inputStream;
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("USage: MissionCount <datafile>");
            //System.exit(1);
        }

        try {
            System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
            int crewcount = 0;
            int misscount = 0;
            InputStream log = getFileInputStream(args[0]);
            Scanner sc = new Scanner(log);
            sc.useDelimiter(Pattern.compile(",|\n"));

            while (sc.hasNext()) {
                String crewMember = sc.next();
                list.add(crewMember);
                String mission = sc.next();
                list.add(mission);
             }
             sc.close();
             // Add code to print the report here
         }catch (Exception e) {
             System.out.println("Error: " + e.getMessage());
         }
    }
}

1 个答案:

答案 0 :(得分:0)

InputStream log = getFileInputStream(args[0]);

将该行更改为: -

File log = new File(args[0])

应该有用!