[英]Write data from Database to File in Java
我正在嘗試將數據庫中的數據寫入文本文件。
文本文件為空。 我試圖度。 這是代碼:
public void writeText()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e)
{
e.printStackTrace();
}
final String DB_URL ="jdbc:mysql://mis-sql.uhcl.edu/gattupalliv3940";
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try
{
conn = DriverManager.getConnection(DB_URL,"gattupalliv3940","1552688");
stat = conn.createStatement();
rs = stat.executeQuery("select * from student_2");
FileWriter fw = new FileWriter("data.txt");
BufferedWriter bw = new BufferedWriter(fw);
String line ="";
while(rs.next())
{
line = rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getDouble(3);
bw.write(line);
bw.newLine();
}
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
conn.close();
rs.close();
stat.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
如果您沒有收到任何錯誤並且文件為空,則唯一可能發生的情況是您的while(rs.next())行在第一次輸入時必須返回false; 這意味着您沒有從數據庫中得到任何東西。
您是否已逐步執行代碼以驗證正在執行哪些行,而哪些行沒有執行?
我懷疑文件未寫入您期望的位置,因為您未指定目錄。 我創建了一個簡單的測試,並將文件寫到Tomcat的目錄下... \\ springsource \\ vfabric-tc-server-developer-2.6.4.RELEASE \\ spring-insight-instance \\ wtpwebapps \\ Junk \\ data.txt(我的項目名為“垃圾郵件”。 下面是我的代碼(沒有數據庫的東西):
@RequestMapping(value="/")
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws IOException{
writeText(request.getRealPath("data.txt"));
return new ModelAndView("home");
}
public void writeText(String path) {
BufferedWriter bw = null;
try {
FileWriter fw = new FileWriter(path);
bw = new BufferedWriter(fw);
String line = "this is only a test";
bw.write(line);
bw.newLine();
}
catch(Exception e) {
e.printStackTrace();
} finally {
if( bw != null ) {
try {
bw.close();
} catch (IOException e) {
// ignore
}
}
}
}
在這里可以使用名為JOConnection的庫。 將此庫從外部導入到您的項目中。
在開始時創建一個文件。
File myDb=new File("file_name");
然后使用此代碼訪問該文件數據庫
Database db=Connection.openConnection(myDb);
然后獲取數據以對象列表的形式寫入db。
ArrayList<Items> itmDetails= (ArrayList<Items> )db.getList("Items");
然后將這些數據添加到文件db
db.addList("Items", itmDetails);
最后
Connection.save();
嘗試從Oracle將日志寫入文件時,我遇到了完全相同的問題。
FileOutputStream為我工作! 希望這對您有用。 我不知道為什么PrintWriter無法正常工作。 必須設置oracle ...
List<String> logs = new LinkedList<String>();
String filepath = "xxx.txt";
System.out.println(filepath);
OutputStream os = null;
try{
for(int i = 0; i < logs.size(); i++) {
os = new FileOutputStream(filepath,true);
os.write(("\n"+logs.get(i)).getBytes(), 0, ("\n"+logs.get(i)).length());
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.