添加了从最后一个元素到ArrayList末尾的信息

时间:2013-05-24 16:39:12

标签: java arraylist indexoutofboundsexception

我的问题很简单。我试图将arrayList的最后一个元素添加到该数组列表的末尾,其行如:

   ArrayList.add(ArrayList.get(ArrayList.size()));

但我得到的是indexOutOfBoundsException。

有没有办法在不登陆异常的情况下执行此操作?快速回答。该行不包含在任何循环中。 arrayList有大小。我已经尝试使用ArrayList.size() - 1无效,这里是它包含的完整代码块。

public class SaveButtonListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        JFileChooser fileChooser = new JFileChooser(".");
        int status = fileChooser.showSaveDialog(null);
        if (status == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            String fileName = selectedFile.getPath();
            File imageFolder = new File(fileName);
            imageFolder.mkdir();

            //tokenizes the path into an arraylist
            String delims = "/";
            ArrayList<String> fileTokensList = new ArrayList<>();
            String[] fileTokens = fileName.split(delims);
            fileTokensList.addAll(Arrays.asList(fileTokens));

            //adds the name of the current image
            fileTokensList.add(fileTokensList.get(fileTokensList.size()));

            //rebuilds all the tokens into one string path
            StringBuilder builder = new StringBuilder();
            for (int s = 0; s < fileTokensList.size(); s++) {
                if (s == 0) {
                    builder.append(fileTokensList.get(s));
                } else {
                    builder.append("/");
                    builder.append(fileTokensList.get(s));
                }
            }
            String textFileName = builder.toString();
            System.out.println(textFileName);
            try {
                File saveFile = new File(textFileName);
                FileWriter fileWriter = new FileWriter(saveFile);
                try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
                    for (int i = 0; i < Driver.vehicleList.size()+1; i++) {

                        //writes the text file (one entry per line
                        bufferedWriter.write(Driver.vehicleList.get(i).getPrice());
                        bufferedWriter.write("\t");
                        bufferedWriter.write(Driver.vehicleList.get(i).getYear());
                        bufferedWriter.write("\t");
                        bufferedWriter.write(Driver.vehicleList.get(i).getMake());
                        bufferedWriter.write("\t");
                        bufferedWriter.write(Driver.vehicleList.get(i).getModel());
                        bufferedWriter.write("\t");
                        bufferedWriter.write(Driver.vehicleList.get(i).getComments());
                        bufferedWriter.newLine();

                        //adds the name of the current image
                        fileTokensList.add(Integer.toString(i));

                        //rebuilds all the tokens into one string path
                        StringBuilder imagePathBuilder = new StringBuilder();
                        for (int s = 0; s < fileTokensList.size(); s++) {
                            if (s == 0) {
                                imagePathBuilder.append(fileTokensList.get(s));
                            } else {
                                imagePathBuilder.append("/");
                                imagePathBuilder.append(fileTokensList.get(s));
                            }
                        }
                        String imageFileName = builder.toString();

                        //resaves the picture to the same place 
                        Path FROM =         Paths.get(Driver.vehicleList.get(i).getCarPicture());
                        Path TO = Paths.get(imageFileName);
                        //overwrite existing file, if exists
                        CopyOption[] options = new CopyOption[]{
                            StandardCopyOption.REPLACE_EXISTING,
                            StandardCopyOption.COPY_ATTRIBUTES
                        };
                        Files.copy(FROM, TO, options);
                    }
                }
            } catch (IOException IO) {
                System.out.println("Error writing to file");
            }
            JOptionPane.showMessageDialog(null, "All your information has been saved");
        }
    }
}

这段代码是为了将文件保存到某个位置,而且我做了很多乱码和重建该路径。我是否已经走了很长的路要走一个简单的解决方案,或者我做得对吗?

3 个答案:

答案 0 :(得分:1)

如果ArrayList.get(int index)值介于0和index之间,

Array.size() - 1将有效。由于您要发送Array.size(),因此您将转到数组的无效位置,从而获得异常。

如何解决这个问题?好吧,你应该发布你想要添加的内容,你会得到答案。

答案 1 :(得分:0)

ArrayList<String> fileTokensList = new ArrayList<>();

您的列表包含字符串,因此您需要获取列表的大小并将其转换为字符串,然后再将其添加到列表中。

list.add( list.size() + "")

执行此操作的一种方法是使用“+”连接运算符,编译器将自动为您创建字符串。

答案 2 :(得分:0)

尝试更改:

ArrayList.add(ArrayList.get(ArrayList.size()));

ArrayList.add(ArrayList.get(ArrayList.size()-1));