Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at com.demo.parsing.MainActivity.main(MainActivity.java:47)
Writer out = new FileWriter(new File(args[0])); (第 47 行)
我是 JAVA 的新手。我一直在尝试这段代码,但找不到这个arrayoutofboundexception
。在这段代码中,我试图从本地 XML 文件中解析一些数据并将其写入一个新文件中。文件已创建但没有文本并出现上述异常
package com.demo.parsing;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.jsoup.Jsoup;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class MainActivity {
//private static OutputStreamWriter out;
public static void main(String[] args) throws FileNotFoundException {
FileInputStream f0 = new FileInputStream("/home/kailash/workspace/paarsing/pustaka-feed.xml");
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document feed = builder.parse(f0);
NodeList items = feed.getElementsByTagName("item");
List<String> urls = new LinkedList<String>();
for (int i = 0; i < items.getLength(); i++) {
Element item = (Element) items.item(i);
Element description = (Element) item.getElementsByTagName(
"description").item(0);
urls.addAll(getImages(builder, description.getTextContent()));
}
Writer out = new FileWriter(new File(args[0]));
for (String url : urls) {
out.write(url + "\n");
}
out.close();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static List<String> getImages(DocumentBuilder builder, String content) throws SAXException, IOException {
List<String> urls = new LinkedList<String>();
for (org.jsoup.nodes.Element img : Jsoup.parse(content).getElementsByTag("img")) {
urls.add(img.attributes().get("src"));
}
return urls;
}
}