无法转换为Write人,发现没有导入import java.io.Writer;,导入后也报错
package com.dom4j;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Writer {
public void writerXml() {
String file = "/Users/weiwen/eclipse-workspace/xml/src/hr-schema.xml";
SAXReader reader = new SAXReader();
try {
Document document = reader.read(file);
Element root = document.getRootElement();
Element employee = root.addElement("employee");
employee.addAttribute("num", "3311");
Element name = employee.addElement("name");
name.setText("zhaotiezhu");
employee.addElement("age").setText("34");
employee.addElement("salary").setText("3400");
Element department = employee.addElement("department");
department.addElement("dname").setText("xx部");
department.addElement("address").setText("xxx");
//
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
document.write(writer);
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
HrWriter hrWriter = new HrWriter();
hrWriter.writerXml();
}
}
正在回答 回答被采纳积分+1
同学你好,报错的原因是,因为同学自定义的类名Writer与java当中的Writer类名相同,导致在创建构造方法时,也就是
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
中会首先找自己定义的Writer类的构造方法,而我们自定义的类中没有此构造方法,并且我们并不是要创建自定义的类中的对象,所以会报错~
建议同学将自定义的类名进行修改为其他类名,如HrWriter ,就可以啦~
具体如下:
右键类名--》Refactor--》Rename
然后进行修改,finish
最后重新导入包。如:
修改后的代码如下:
import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class HrWriter { public void writerXml() { String file = "/Users/weiwen/eclipse-workspace/xml/src/hr-schema.xml"; SAXReader reader = new SAXReader(); try { Document document = reader.read(file); Element root = document.getRootElement(); Element employee = root.addElement("employee"); employee.addAttribute("num", "3311"); Element name = employee.addElement("name"); name.setText("zhaotiezhu"); employee.addElement("age").setText("34"); employee.addElement("salary").setText("3400"); Element department = employee.addElement("department"); department.addElement("dname").setText("xx部"); department.addElement("address").setText("xxx"); // Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); document.write(writer); writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { HrWriter hrWriter = new HrWriter(); hrWriter.writerXml(); } }
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星