我写了一个这样的简单函数:
private static void write(String Swrite) throws IOException {
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file);
if(Swrite!=null)
fop.write(Swrite.getBytes());
fop.flush();
fop.close();
}
Run Code Online (Sandbox Code Playgroud)
每次我调用它,它都会重写,然后我就会得到最后写的项目.如何将其更改为不重写?的file变量是全局定义为File.
我决定实现摘要List<Node>.这是它的一部分:
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class myNodeList implements NodeList{
Node root = null;
int length = 0;
public myNodeList() {}
public void addNode(Node node) {
if(root == null)
{
root = node;
}
else
root.appendChild(node);
length++;
System.out.println("this is the added node " +node);
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试add一个节点时,它给了我以下异常:
Exception in thread "main" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
at com.sun.org.apache.xerces.internal.dom.NodeImpl.insertBefore(NodeImpl.java:478)
at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(NodeImpl.java:235)
at pageparsertest.myNodeList.addNode(myNodeList.java:27)
Run Code Online (Sandbox Code Playgroud)
这是因为Node root = …
每当我运行以下代码时它给了我,NullPointerException.虽然我检查是否不为null然后添加,但仍然给出了eception.the file是一个纯文本(.txt)
什么可能是错的?
BufferedReader br2 = new BufferedReader(new FileReader(file));
ArrayList<String> keArrayList=null;
for(int i=0;br2.readLine()!=null;i++)
{
String letter= br2.readLine();
if (letter!=null)
keArrayList.add(i,letter);
}
Run Code Online (Sandbox Code Playgroud)