【发布时间】:2021-06-25 06:30:00
【问题描述】:
我在保留/保存保存在我的 GUI 表中的值时遇到问题。我的目标是保留它存储在表中的值,退出我的 GUI,然后再次打开它,然后我希望看到存储在表中的相同值。我的问题是,每当我关闭并再次打开 GUI 时,它都会刷新值并再次使其空白。
我通过写入和读取 CSV 文件来保存我的值。
在编写 CSV 文件时,它取决于用户在我的 GUI 的文本字段中输入的值,然后它会在我的驱动器 C 中的特定位置创建一个 CSV 文件。
在读取 CSV 文件时,它会读取写入的 CSV 文件的内容/值,然后使用这些值存储在二维数组中,以便将其显示到我的表格中。但问题是我无法在表中保留这些值,而且表显示空值,就在显示的数据旁边(我尝试执行 != null 但它仍然在输入值之后显示连续的空值)
这是我的源代码:
public void writeCustomerCSV(){ // everything in this snippet code works fine(it creates a CSV file which stores the inputs of the user)
try{
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
StringBuilder sb = new StringBuilder();
int y;
for(int x = 0; x < itemTo2D.length; x++){
for(y = 0; y < itemTo2D[0].length; y++){
if(itemTo2D[x] != null){
sb.append(itemTo2D[x][y]);
sb.append(",");
}
}
sb.append("-"); //separation for rows
sb.append(","); // separation for columns
}
bw.write(sb.toString());
bw.close();
} catch (Exception ex){
}
}
public void readCustomerCSV(){ // reads the contents of the CSV file *having issues in retaining the values
int read2DStringIndex = 0;
int newVarIndexer = 0;
String[] fromfile = {}; // 1d string for getting the columns(7 columns) of the CSV file
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
String line;
while ((line = br.readLine()) != null){
fromfile = line.split(","); //separates the columns by a comma
}
} catch (Exception ex){
}
for(int g = 0; g < fromfile.length; g++){
if(fromfile[g].equals("-")){ //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
read2DStringIndex++;
newVarIndexer = 0;
}
else{
cust[read2DStringIndex][newVarIndexer] = fromfile[g]; //cust is the 2D array(declared universal) which is going to display the values to the table
newVarIndexer++;
}
}
for(int h = 0; h < cust.length; h++){ //prints cust (2D array) , just to check what data is being stored
for(int p = 0; p < cust[0].length; p++){
System.out.println(cust[h][p] + ",");
}
}
DefaultTableModel tblmodelll = (DefaultTableModel) mainTable.getModel(); // table
setrowcount = 0;
for(int r = 0; r < cust.length; r++){
if(setrowcount == 0){
tblmodelll.setRowCount(0);
}
if(cust[r][0] != null){
tblmodelll.addRow(cust[r]); //displays the cust(2D array) data to table
}
setrowcount++;
}
}
我是否遗漏了要在我的代码中添加的内容,或者代码的逻辑不正确? 您的回复确实有助于解决此问题。 非常感谢!!!
【问题讨论】:
-
两个问题很突出 - a) 如果用户输入 A,B 作为值或 AB 会怎样,以及 b) CSV 通常是行逐行读取/写入第 0 行的所有列作为一行,然后再次读取第 1 行,然后第 2 行......(注意:除了多行的值......)
-
也许阅读此类问题的先前答案 - stackoverflow.com/a/14226913 - 会提供一些其他想法。
-
您可以使用 gson 来保存和加载整个内容,也可以自己使用 JsonReader 和 JsonWriter 实现加载逻辑
-
修改模型的代码是否对静态输入做一些理智的事情(即不读取文件只是用一些静态数组调用它以查看它的行为是否正确/将问题拆分为 2,检查您的 CSV 读/写往返并检查 GUI 填充)。
-
@IntoVoid 哦,好的,我会看看我能用 JsonReader 和 JsonWriter 做什么。 itemTo2D 也是一个二维字符串数组。
标签: java csv user-interface multidimensional-array