java 将 JTable 保存为文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14166269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving JTable as text file
提问by Patrick Dibb
I am saving a .txt and .doc file containing the data from my JTable. At the minute when it saves it lays the text out like its in a table, but due to different lengths of data it does not fit. So I am trying to get the date to lay out as follows:
我正在保存一个 .txt 和 .doc 文件,其中包含来自我的 JTable 的数据。在它保存的那一刻,它会像在表格中一样排列文本,但由于数据长度不同,它不适合。所以我试图让日期布置如下:
Column 1 name: row 1 column 1 data
第 1 列名称:第 1 行第 1 列数据
Column 2 name: row 1 column 2 data
第 2 列名称:第 1 行第 2 列数据
Column 3 name: row 1 column 3 data
第 3 列名称:第 1 行第 3 列数据
Column 4 name: row 1 column 4 data
第 4 列名称:第 1 行第 4 列数据
Column 1 name: row 2 column 1 data
第 1 列名称:第 2 行第 1 列数据
Column 2 name: row 2 column 2 data
第 2 列名称:第 2 行第 2 列数据
Column 3 name: row 2 column 3 data
第 3 列名称:第 2 行第 3 列数据
Column 4 name: row 2 column 4 data
第 4 列名称:第 2 行第 4 列数据
etc.
等等。
The code I have at the minute is:
我现在的代码是:
private void saveResultsActionPerformed(ActionEvent evt) {
int returnVal = fileChooser.showSaveDialog(NewJFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
PrintWriter os = new PrintWriter(file);
os.println("");
for (int col = 0; col < table.getColumnCount(); col++) {
os.print(table.getColumnName(col) + "\t");
}
os.println("");
os.println("");
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
os.print(table.getValueAt(i, j).toString() + "\t");
}
os.println("");
}
os.close();
System.out.println("Done!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But please keep in mind that each of my tables has different number of columns and rows. Ive tried saving the columns and data in arrays, and I have a feeling this is the right way to go around the problem but I cant figure out how to print it in the order i mentioned,
但请记住,我的每个表都有不同数量的列和行。我试过将列和数据保存在数组中,我觉得这是解决问题的正确方法,但我不知道如何按照我提到的顺序打印它,
回答by JB Nizet
The algorithm is quite simple:
算法非常简单:
for (int row = 0; row < table.getRowCount(); row++) {
for (int col = 0; col < table.getColumnCount(); col++) {
os.print(table.getColumnName(col));
os.print(": ");
os.println(table.getValueAt(row, col));
}
}
回答by Snorre
A minimal example I made is provided below. I gives the following form of output:
下面提供了我制作的一个最小示例。我给出了以下形式的输出:
First Name: Kathy
Last Name: Smith
Sport: Snowboarding
# of Years: 5
名字:Kathy
姓氏:Smith
运动:滑雪
年数:5
First Name: John
Last Name: Doe
Sport: Rowing
# of Years: 2
名字:约翰
姓氏:Doe
Sport:划船
年数:2
String[] columnNames = {"First Name", "Last Name","Sport","# of Years"};
Object[][] data = {
{"Kathy", "Smith", "Snowboarding", "5"},
{"John", "Doe", "Rowing", "2"},
{"Sue", "Black", "Knitting", "8"},
{"Jane", "White", "Speed reading", "10"},
{"Joe", "Brown", "Pool", "20"}
};
JTable table = new JTable(data, columnNames);
for(int row = 0; row < table.getRowCount(); row++) {
for(int column = 0; column < table.getColumnCount(); column++) {
System.out.print(table.getColumnName(column) + ": ");
System.out.println(table.getValueAt(row, column));
}
System.out.println(""); // Add line space
}
回答by silence
The following code uses substrings to allow for the columns to be orderly within the textfile. Its a bit messy but the first for loop handles column headers and the second for loop handles all the data. If you want to change the size of each piece of data change 20 to your prefered size.
以下代码使用子字符串来允许列在文本文件中有序。它有点乱,但第一个 for 循环处理列标题,第二个 for 循环处理所有数据。如果要更改每条数据的大小,请将 20 更改为您喜欢的大小。
BufferedWriter bfw = new BufferedWriter(new FileWriter(
"Data.txt"));
for (int i = 0; i < table.getColumnCount(); i++) {//first loop is used for titles of each column
String name = String.valueOf(table.getColumnName(i));
if (name.length() > 20) {//20 (characters long) is the constant I chose to make each value
name = name.substring(0, 20);
} else if (name.length() == 20) {
} else {
String spaces = "";
int diff = 20 - name.length();
while (diff > 0) {
spaces = spaces + " ";
diff--;
}
name = name.concat(spaces);
}
bfw.write(name);
bfw.write("\t");
}
for (int i = 0; i < table.getRowCount(); i++) {//for all the data in the Jtable excluding column headers
bfw.newLine();
for (int j = 0; j < table.getColumnCount(); j++) {
if (table.getValueAt(i, j) == null) {
bfw.write(" ");
bfw.write("\t");
}
else {
String name = String.valueOf((table
.getValueAt(i, j)));
if (name.contains("(")) {
name = name.substring(0, name.indexOf("("));
}
if (name.length() > 20) {
name = name.substring(0, 20);
} else if (name.length() == 20) {
} else {
String spaces = "";
int diff = 20 - name.length();
while (diff > 0) {
spaces = spaces + " ";
diff--;
}
name = name.concat(spaces);
}
bfw.write(name);
bfw.write("\t");
}
}
}
回答by Mark Burleigh
In addition to the answers already provided, I have implemented a solution which saves the contents to a text file of type .csv (Comma-Separated Values).
除了已经提供的答案之外,我还实施了一个解决方案,将内容保存到 .csv(逗号分隔值)类型的文本文件中。
Firstly, I have created a method which places the contents of a JTable into a two-dimensional array of type Object. I have chosen the type Object because various columns within a JTable may store different types of data e.g. numbers, Strings etc. This method is located within my GUI front-end:
/** * * This method extrapolates the data from the JTable and places * it into a two-dimensional object array. <p> * * It then returns the object array in preparation for writing to disk * * * @param aTable - the selected table for rendering into a two- dimensional object array * * @return Object[][] - the two-dimensional object array which shall be written to disk * * @see * */ public Object[][] getTableData(JTable aTable) { int rowCount = aTable.getModel().getRowCount(); int columnCount = aTable.getModel().getColumnCount(); Object[][] curTableData = new Object[rowCount][columnCount]; for ( int row = 0; row < rowCount; row++) { for (int column = 0; column < columnCount; column++) { curTableData[row][column] = aTable.getModel().getValueAt(row,column); // System.out.println("curTableData["+row+"]["+column+"] = "+curTableData[row][column]); } } return curTableData; }
Secondly, I have created a class that is responsible for writing the contents of the two-dimensional object array (JTable contents) to disk. This is outlined below:
import java.io.*; /** * * This class is responsible for writing the 2D object to disk. * The 2d Object contains your JTable contents * <p> * * @author Mark Burleigh * @version %I%, %G% * @since 1.0 * */ public class WriteJTableContents { /** * * This constructor takes in two parameters. It is also responsible * for writing the JTable contents to disk (to csv file) * * * @param aData - the JTable data to be saved to disk * @param afile - the name of the file where the data shall be saved * (this is a .CSV type file) * * */ public WriteRandomSampleData(Object[][] aData, String afile) { writeToDisk(aData,afile); // This method prints the two-dimensional array to the command console // printData(); } /** * * This method is responsible for writing the contents of a JTable (2d * array object) to disk (csv text file) * <p> * * @param aData - the 2D data (Jtable contents) to be stored to disk * @param aDatafile - the file where the data shall be stored * to disk. This shall be of type.CSV * * @return * * @see * */ public void writeToDisk(Object[][] aData, String aDatafile) { try { FileOutputStream fout = new FileOutputStream(aDatafile, false); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fout)); //Headers bw.append("Script No., Candidate No., Mark, Grade,Script No., Candidate No., Mark, Grade"); // End of data row (Jable row) so append new line character in csv file bw.append('\n'); for (int row = 0; row < aData.length; row++) { for (int column = 0; column < aData[row].length; column++) { if(aData[row][column] == null) { bw.append("null"); // The comma separated value bw.append(','); } else { /* In my particular example, I am doing some checking on the 2d array for types: if the data is not of type null (as checked above) then it must be of type Integer. This is because the 2D data array only contains data of either Integer or null each of these object types have a method called toString(). we need this in order to convert the types to a string prior to wrting them to the file. */ bw.append(aData[row][column].toString()); bw.append(','); } }//end column loop (inner loop) bw.append('\n'); }//end row loop (outer loop) bw.close(); } catch (Exception e) { e.getStackTrace(); } }//end of readFileFromDisk /** * * These methods is responsible for printing the random sample scripts * Into the command console. * <p> * * */ public void printData() { //System.out.println(); //System.out.println("=======WriteRandomSampleData Class==========="); //System.out.println(); for (int row = 0; row < data.length; row++) { for (int column = 0; column < data[row].length; column++) { System.out.println("data["+row+"]["+column+"] = " +data[row][column]); } } } //==================Instance Variables============================= // JTable contents hedata private Object[][] data; //====================Test Driver============================ public static void main(String args[]) { // file seperator for windows platform '\' String aFileLocation = "C:\dirA\subdir1\subdir2\"; // Dummy values - 2D array which stores the contents of a // JTable into a csv text file Object[][] testData = new Object [][] { {new Integer(1),new Integer(1),null,null,new Integer(11),new Integer(1),null,null}, {new Integer(2),new Integer(1),null,null,new Integer(12),new Integer(1),null,null}, {new Integer(3),new Integer(1),null,null,new Integer(13),new Integer(1),null,null}, {new Integer(4),new Integer(1),null,null,new Integer(14),new Integer(1),null,null}, {new Integer(5),new Integer(1),null,null,new Integer(15),new Integer(1),null,null}, {new Integer(6),new Integer(1),null,null,new Integer(16),new Integer(1),null,null}, {new Integer(7),new Integer(1),null,null,new Integer(17),new Integer(1),null,null}, {new Integer(8),new Integer(1),null,null,new Integer(18),new Integer(1),null,null}, {new Integer(9),new Integer(1),null,null,new Integer(19),new Integer(1),null,null}, {new Integer(10),new Integer(1),null,null,new Integer(20),new Integer(1),null,null} }; // SampleData_TEST.csv gets created in the particular directory // and the file gets populated with the contents of the JTable new WriteRandomSampleData(testData,aFileLocation2+"SampleData_TEST.csv"); } }
首先,我创建了一个方法,将 JTable 的内容放入 Object 类型的二维数组中。我选择了对象类型,因为 JTable 中的各个列可能存储不同类型的数据,例如数字、字符串等。此方法位于我的 GUI 前端中:
/** * * This method extrapolates the data from the JTable and places * it into a two-dimensional object array. <p> * * It then returns the object array in preparation for writing to disk * * * @param aTable - the selected table for rendering into a two- dimensional object array * * @return Object[][] - the two-dimensional object array which shall be written to disk * * @see * */ public Object[][] getTableData(JTable aTable) { int rowCount = aTable.getModel().getRowCount(); int columnCount = aTable.getModel().getColumnCount(); Object[][] curTableData = new Object[rowCount][columnCount]; for ( int row = 0; row < rowCount; row++) { for (int column = 0; column < columnCount; column++) { curTableData[row][column] = aTable.getModel().getValueAt(row,column); // System.out.println("curTableData["+row+"]["+column+"] = "+curTableData[row][column]); } } return curTableData; }
其次,我创建了一个类,负责将二维对象数组的内容(JTable 内容)写入磁盘。概述如下:
import java.io.*; /** * * This class is responsible for writing the 2D object to disk. * The 2d Object contains your JTable contents * <p> * * @author Mark Burleigh * @version %I%, %G% * @since 1.0 * */ public class WriteJTableContents { /** * * This constructor takes in two parameters. It is also responsible * for writing the JTable contents to disk (to csv file) * * * @param aData - the JTable data to be saved to disk * @param afile - the name of the file where the data shall be saved * (this is a .CSV type file) * * */ public WriteRandomSampleData(Object[][] aData, String afile) { writeToDisk(aData,afile); // This method prints the two-dimensional array to the command console // printData(); } /** * * This method is responsible for writing the contents of a JTable (2d * array object) to disk (csv text file) * <p> * * @param aData - the 2D data (Jtable contents) to be stored to disk * @param aDatafile - the file where the data shall be stored * to disk. This shall be of type.CSV * * @return * * @see * */ public void writeToDisk(Object[][] aData, String aDatafile) { try { FileOutputStream fout = new FileOutputStream(aDatafile, false); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fout)); //Headers bw.append("Script No., Candidate No., Mark, Grade,Script No., Candidate No., Mark, Grade"); // End of data row (Jable row) so append new line character in csv file bw.append('\n'); for (int row = 0; row < aData.length; row++) { for (int column = 0; column < aData[row].length; column++) { if(aData[row][column] == null) { bw.append("null"); // The comma separated value bw.append(','); } else { /* In my particular example, I am doing some checking on the 2d array for types: if the data is not of type null (as checked above) then it must be of type Integer. This is because the 2D data array only contains data of either Integer or null each of these object types have a method called toString(). we need this in order to convert the types to a string prior to wrting them to the file. */ bw.append(aData[row][column].toString()); bw.append(','); } }//end column loop (inner loop) bw.append('\n'); }//end row loop (outer loop) bw.close(); } catch (Exception e) { e.getStackTrace(); } }//end of readFileFromDisk /** * * These methods is responsible for printing the random sample scripts * Into the command console. * <p> * * */ public void printData() { //System.out.println(); //System.out.println("=======WriteRandomSampleData Class==========="); //System.out.println(); for (int row = 0; row < data.length; row++) { for (int column = 0; column < data[row].length; column++) { System.out.println("data["+row+"]["+column+"] = " +data[row][column]); } } } //==================Instance Variables============================= // JTable contents hedata private Object[][] data; //====================Test Driver============================ public static void main(String args[]) { // file seperator for windows platform '\' String aFileLocation = "C:\dirA\subdir1\subdir2\"; // Dummy values - 2D array which stores the contents of a // JTable into a csv text file Object[][] testData = new Object [][] { {new Integer(1),new Integer(1),null,null,new Integer(11),new Integer(1),null,null}, {new Integer(2),new Integer(1),null,null,new Integer(12),new Integer(1),null,null}, {new Integer(3),new Integer(1),null,null,new Integer(13),new Integer(1),null,null}, {new Integer(4),new Integer(1),null,null,new Integer(14),new Integer(1),null,null}, {new Integer(5),new Integer(1),null,null,new Integer(15),new Integer(1),null,null}, {new Integer(6),new Integer(1),null,null,new Integer(16),new Integer(1),null,null}, {new Integer(7),new Integer(1),null,null,new Integer(17),new Integer(1),null,null}, {new Integer(8),new Integer(1),null,null,new Integer(18),new Integer(1),null,null}, {new Integer(9),new Integer(1),null,null,new Integer(19),new Integer(1),null,null}, {new Integer(10),new Integer(1),null,null,new Integer(20),new Integer(1),null,null} }; // SampleData_TEST.csv gets created in the particular directory // and the file gets populated with the contents of the JTable new WriteRandomSampleData(testData,aFileLocation2+"SampleData_TEST.csv"); } }
The contents of the resulting SampleData_TEST.csv file are outlined below:
生成的 SampleData_TEST.csv 文件的内容概述如下:
As depicted above, the csv file format can be opened in Microsoft Excel which can be more versatile (depending on the type of data) than a .doc or .txt file
如上所示,csv 文件格式可以在 Microsoft Excel 中打开,它比 .doc 或 .txt 文件更通用(取决于数据类型)