我想在用户指定的目录中有一个XML文件。为此,我已经创建了一个文件专家。
File file = new File("d:Expert");
这是创建文件export .xml在d: drive。但是这里我已经提到了程序本身的路径。但用户无法识别此路径。我需要做的是,用户应该在输出控制台中指定他想要的路径。为此,我在args[]中传递了变量。在net beans中,我通过object ->run->arguments->d的属性给出了参数:…后来在程序中,我写了如下代码。这就给出了输出。但是文件没有创建在d:…它只是附加字符串。如何在指定目录下创建文件??谁能提供我的代码片段??
public class New {
void Expor() throws IOException, TransformerConfigurationException
//adding a node after the last child node of the specified node.
Element child = doc.createElement("body");
root.appendChild(child);
System.out.println("file created successfully");
//TransformerFactory instance is used to create Transformer objects.
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = sw.toString();
File file = new File("expert");// creates the file if i mentioned D:/Export.xml
//System.out.println(file.getName());
// System.out.println(file.getAbsolutePath());
String path=readpath+filename;
System.out.println(path);
BufferedWriter bw = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(xmlString);
bw.flush();
bw.close();
}
public static void main(String argv[]) throws SQLException, IOException,
{
if (argv.length == 0) {
System.out.println("No Command Line arguments");
} else {
System.out.println("You provided " + argv.length
+ " arguments");
for (int i = 0; i < argv.length; i++) {
System.out.println("args[" + i + "]: "
+ argv[i]);
}
}
New e= new New ();
e.connectDB();
}
}
根据您目前提供的内容(这有点乱,而且很难阅读),看起来您想做2个更改:
1: 把你的main方法改成:
public static void main(String argv[]) throws Exception
{
New e= new New ();
e.connectDB();
if(argv.length == 0)
e.xmlExport("D:\export.xml");
else
e.xmlExport(argv[0]);
}
2: 将你的xmlExport方法改为:
void xmlExport(String fileName) throws IOException, TransformerConfigurationException
{
// ...
File file = new File(fileName);
// ...
}
如果这不是你想要的,那么你需要更清楚地解释你的问题。
(如果我理解正确的话)为用户提供一个JFileChooser
。