Pregunta

so I am trying to read a file and add two lines of code to it at the top. So far that hadn't been working so I tried just reading the lines and writing them back. This was a major failure. It only writes to one of the files in the directory and just keeps filling it with the xmlopentag even though its been commented out, over and over. If anyone has any ideas it would be appreciated.

ArrayList<String> lines = new ArrayList();
        BufferedReader reader = null;
        String xmlstylesheet = "<?xml-stylesheet type=\"text/xsl\" href=\""+stylefilename+"\"?>";
        String xmlopentag = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        for(int i=0;i<files.length;i++) {
            lines.clear();
            try {
                reader = new BufferedReader(new FileReader(files[i]));
                String text = null;
                while ((text = reader.readLine()) != null) {
                    lines.add(text);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            }
            //lines.add(1, xmlstylesheet);
            //lines.add(0, xmlopentag);
            try {
                PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(files[i])));
                for(int j=0;j<lines.size();j++) {
                    writer.write(lines.get(i));
                }
            } catch (IOException ex) {
                Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
¿Fue útil?

Solución

writer.write(lines.get(i)); 

should probably be

writer.write(lines.get(j));

Otros consejos

for loop for PrintWriter operation is having an index j for iteration but using i to get the list value

please check it properly and change below code

for(int j=0;j<lines.size();j++) {
                    writer.write(lines.get(i));
                }

to

for(int j=0;j<lines.size();j++) {
                    writer.write(lines.get(j));
                }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top