我要求导出用户以CSV格式下载的mysql表数据。
为了实现这一点,我正在尝试java运行时exec函数并执行" mysql -e"。不幸的是,我被困在一半。我只能将sql输出显示到控制台,但无法将其路由到文件。
(我能在eclipse控制台中看到记录)
try {
Process p = Runtime.getRuntime().exec(new String[]
{
"mysql","-h","localhost","-u","admin","-pxyz","myDB","-e", "\"select concat(billing_amount,',') as 'Billing Amount,', concat(amount_paid ,',') as 'Amount Paid,' from invoice\""
}
);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
//process.waitFor();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但是当我尝试使用">将数据导出到文件时abc.txt" ,文件未创建,而是在eclipse控制台中看到mySQL --help选项。这可能有什么问题?
try {
Process p = Runtime.getRuntime().exec(new String[]
{
"mysql","-h","localhost","-u","admin","-pxyz","myDB","-e", "\"select concat(billing_amount,',') as 'Billing Amount,', concat(amount_paid ,',') as 'Amount Paid,' from invoice\"", "> abc.txt"
}
);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
//process.waitFor();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:0)
I / O重定向由shell处理,而不是由每个程序处理。因此,mysql
不知道如何处理> abc.txt
。执行shell并将完整命令作为单个参数传递,就像在Unix系统中一样:
Process p = Runtime.getRuntime().exec(new String[] {
"sh", "-c", "mysql -h localhost -u admin -pxyz myDB -e \"select concat(billing_amount,',') as 'Billing Amount,', concat(amount_paid ,',') as 'Amount Paid,' from invoice\" > abc.txt"
});
但更好的选择是不使用Unix shell,而是使用ProcessBuilder
和redirectOutput(File)
方法。