我的 jTable 有问题。我在网上看了很多资料,但仍然无法解决我的问题。当我单击 jButton1 时,将调用此过程(保存到 jtable 的文本文件)
public void SaveMyTable()throws Exception
{
BufferedWriter bfw = new BufferedWriter(new FileWriter("C:\\emma\\mystuff\\database.txt"));
for(int i = 0 ; i < jTable1.getColumnCount() ; i++)
{
bfw.write(jTable1.getColumnName(i));
bfw.write("\t");
}
for (int i = 0 ; i < jTable1.getRowCount(); i++)
{
bfw.newLine();
for(int j = 0 ; j < jTable1.getColumnCount();j++)
{
bfw.write((String)(jTable1.getValueAt(i,j)));
bfw.write("\t");;
}
}
bfw.close();
}
通过这段代码,我以这种方式保存数据:
n Col1 Col2 Col3
1 a b c
我希望当程序运行时,它从上面的路径加载这个文件,所以我想使用 BufferedReader 方法。顺便说一句,我不知道该怎么做。你有什么想法? :) 在这里你可以看到我的代码,我只做了其中的一部分,因为我不知道如何继续。
public void LoadMyTable()throws Exception
{
BufferedReader br = new BufferedReader(new FileReader("C:\\addressbook\\databese.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
// code that loads the datas in my jTable
} finally {
br.close();
}
最佳答案
你需要这样的东西。
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(path));
String line = null;
while ((line = br.readLine()) != null) {
//here you have to load your table
}
} catch (IOException e) {
//manage your exceptions
} finally {
try {
if (br != null){
br.close(); // close open streams resources
}
} catch (IOException ex) {
//manage your exceptions
}
}
readLine() :读取一行文本。一行被视为由换行符 ('\n')、回车符 ('\r') 或回车符后紧跟换行符之一终止。
五月 this帮助你
关于java - 将JTable内容保存到文本文件并读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17179592/