如何将每行的前三个单词放入arraylist?

时间:2017-11-06 19:45:58

标签: java file arraylist

public class scripttest {

    public static void main(String[] args) {
        File file = new File("text.txt");
        script(file);
    }

    public static void script(File filename) {
        String line = null;
        try {
            FileReader fileReader = new FileReader(filename);

            BufferedReader bufferedReader = new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null)
            {
                System.out.println(line);
            }

            bufferedReader.close();
        } catch(IOException ex) {
            System.out.println("Error reading file named '" + filename + "'");
        }
    }
}

我试图为我的程序创建一个脚本函数,该脚本需要一个文件,每个命令写出的每个命令都要连续执行。如何将每行的前三个单词添加到一个arraylist,然后用于解释每一行的命令?

2 个答案:

答案 0 :(得分:0)

// considering you have line variable. myArrayList is ur list. 

String[] words = line.split(" ");
if(words.length() >= 3) {
   myArrayList.add(words[0] + " " + words[1] + " " + words[2])
}

答案 1 :(得分:0)

如果您可以使用Java 8:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TestScript {
    public static void main(String[] args) {
        script("text.txt");
    }

    private static void script(String filename) {
        try (Stream<String> stream = Files.lines(Paths.get(filename))) {
            stream.forEach(TestScript::executeLine);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void executeLine(String line) {
        System.out.println(line);

        String[] args = line.split(" ");
        executeCommand(Arrays.stream(args).limit(3).collect(Collectors.toList()),
                Arrays.stream(args).skip(3).collect(Collectors.toList()));
    }

    private static void executeCommand(List<String> command, List<String> args) {
        System.out.println(command + ": " + args);
    }
}