如何在java中更新txt文件
我有一个JTable,其中显示文本文件中的数据: 现在,对于删除,我有如下方法:如何在java中更新txt文件,java,swing,jtable,text-files,Java,Swing,Jtable,Text Files,我有一个JTable,其中显示文本文件中的数据: 现在,对于删除,我有如下方法: private void delete(ActionEvent evt) { DefaultTableModel model = (DefaultTableModel) tblRooms.getModel(); // get selected row index try { int SelectedRowIndex = tblRooms.getSelectedRow();
private void delete(ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) tblRooms.getModel();
// get selected row index
try {
int SelectedRowIndex = tblRooms.getSelectedRow();
model.removeRow(SelectedRowIndex);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
和动作监听器:
btnDelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
delete(e);
}
});
它将删除JTable中的行,这没问题,但我的文本文件有7个拆分,其中最后一个拆分用于逻辑删除。所以,如果false-room没有被删除
13|family room|name apartman|4|true|true|true|false
14|superior room|super room|2|true|false|false|false
15|room|room for one|1|false|false|true|false
0|MisteryRoom|Mistery|0|true|true|free|false
如何以正确的方式从JTable中删除特定房间,并从false更改为true?
例如,如果我单击super room,如何准确地删除该文件室。出于许多原因,最好使用数据库而不是文本文件来处理这类事情,因为您使用文本文件作为数据存储,因此我将演示一种替换值(子字符串)的方法在特定的数据文本文件行中 现在,以下方法可用于修改任何文件数据行上的任何字段数据…甚至是房间号,因此请记住这一点。您需要确保仅在最好的情况下进行修改:
/**
* Updates the supplied Room Number data within a data text file. Even the
* Room Number can be modified.
*
* @param filePath (String) The full path and file name of the Data File.
*
* @param roomNumber (Integer - int) The room number to modify data for.
*
* @param fieldToModify (Integer - int) The field number in the data line to
* apply a new value to. The value supplied here is to be considered 0 based
* meaning that 0 actually means column 1 (room number) within the file data
* line. A value of 7 would be considered column 8 (the deleted flag).
*
* @param newFieldValue (String) Since the file is string based any new field
* value should be supplied as String. So to apply a boolean true you will need
* to supply "true" (in quotation marks) and to supply a new room number that
* room number must be supplied a String (ie: "666").
*
* @return (Boolean) True if successful and false if not.
*/
public boolean updateRoomDataInFile(String filePath, int roomNumber,
int fieldToModify, String newFieldValue) {
// Try with resources so as to auto close the BufferedReader.
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
// Add the data file contents to a List interface...
List<String> dataList = new ArrayList<>();
while ((line = reader.readLine()) != null) {
dataList.add(line);
}
for (int i = 0; i < dataList.size(); i++) {
line = dataList.get(i).trim(); // Trim off any leading or trailing whitespaces (if any).
// Skip Blank lines (if any) and skip Comment lines (if any).
// In this example file comment lines start with a semicolon.
if (line.equals("") || line.startsWith(";")) {
continue;
}
//Split each read line so as to collect the desired room number
// since everything will always be based from this unique ID number.
// Split is done baesed on the Pipe (|) character since this is
// what is implied with your data example.
String[] roomData = line.split("\\|");
// Get the current file data line room number.
// Make sure the first piece of data is indeed a valid integer room
// number. We use the String.matches() method for this along with a
// regular expression.
if (!roomData[0].trim().matches("\\d+")) {
// If not then inform User and move on.
JOptionPane.showMessageDialog(null, "Invalid room number detected on file line: "
+ (i + 1), "Invalid Room Number", JOptionPane.WARNING_MESSAGE);
continue;
}
// Convert the current data line room number to Integer
int roomNum = Integer.parseInt(roomData[0]);
// Does the current data line room number equal the supplied
// room number?
if (roomNum != roomNumber) {
// If not then move on...
continue;
}
// If we reach this point then we know that we are currently on
// the the data line we need and want to make changes to.
String strg = ""; // Use for building a modified data line.
// Iterate through the current data line fields
for (int j = 0; j < roomData.length; j++) {
// If we reach the supplied field number to modify
// then we apply that modification to the field.
if (j == fieldToModify) {
roomData[j] = newFieldValue;
}
// Build the new data line. We use a Ternary Operator, it is
// basicaly the same as using a IF/ELSE.
strg += strg.equals("") ? roomData[j] : "|" + roomData[j];
}
// Replace the current List element with the modified data.
dataList.set(i, strg);
}
// Rewrite the Data File.
// Try with resources so as to auto close the FileWriter.
try (FileWriter writer = new FileWriter(filePath)) {
// Iterate through the List and write it to the data file.
// This ultimately overwrites the data file.
for (int i = 0; i < dataList.size(); i++) {
writer.write(dataList.get(i) + System.lineSeparator());
}
}
// Since no exceptions have been caught at this point return true
// for success.
return true;
}
catch (FileNotFoundException ex) {
Logger.getLogger("updateFileRoomStatus()").log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger("updateFileRoomStatus()").log(Level.SEVERE, null, ex);
}
// We must of hit an exception if we got
// here so return false for failure.
return false;
}
在上面的代码中,提供了数据文件名“HotelRoomsData.txt”。当然,这假定数据文件包含该名称,并且该名称位于特定项目的根文件夹(目录)中。如果文件的名称不同,并且位于完全不同的位置,则需要将其更改为数据文件的完整路径和文件名,例如:
"C:/Users/Documents/MyDataFile.txt"
代码并没有那么长,只是有很多注释伴随着它来解释事情。当然,这些注释可以从代码中删除。出于许多原因,最好使用数据库而不是文本文件来处理这类事情,尤其是当您使用文本文件作为数据存储时,我将演示一种替换特定数据文本文件行中的值(子字符串)的方法 现在,以下方法可用于修改任何文件数据行上的任何字段数据…甚至是房间号,因此请记住这一点。您需要确保仅在最好的情况下进行修改:
/**
* Updates the supplied Room Number data within a data text file. Even the
* Room Number can be modified.
*
* @param filePath (String) The full path and file name of the Data File.
*
* @param roomNumber (Integer - int) The room number to modify data for.
*
* @param fieldToModify (Integer - int) The field number in the data line to
* apply a new value to. The value supplied here is to be considered 0 based
* meaning that 0 actually means column 1 (room number) within the file data
* line. A value of 7 would be considered column 8 (the deleted flag).
*
* @param newFieldValue (String) Since the file is string based any new field
* value should be supplied as String. So to apply a boolean true you will need
* to supply "true" (in quotation marks) and to supply a new room number that
* room number must be supplied a String (ie: "666").
*
* @return (Boolean) True if successful and false if not.
*/
public boolean updateRoomDataInFile(String filePath, int roomNumber,
int fieldToModify, String newFieldValue) {
// Try with resources so as to auto close the BufferedReader.
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
// Add the data file contents to a List interface...
List<String> dataList = new ArrayList<>();
while ((line = reader.readLine()) != null) {
dataList.add(line);
}
for (int i = 0; i < dataList.size(); i++) {
line = dataList.get(i).trim(); // Trim off any leading or trailing whitespaces (if any).
// Skip Blank lines (if any) and skip Comment lines (if any).
// In this example file comment lines start with a semicolon.
if (line.equals("") || line.startsWith(";")) {
continue;
}
//Split each read line so as to collect the desired room number
// since everything will always be based from this unique ID number.
// Split is done baesed on the Pipe (|) character since this is
// what is implied with your data example.
String[] roomData = line.split("\\|");
// Get the current file data line room number.
// Make sure the first piece of data is indeed a valid integer room
// number. We use the String.matches() method for this along with a
// regular expression.
if (!roomData[0].trim().matches("\\d+")) {
// If not then inform User and move on.
JOptionPane.showMessageDialog(null, "Invalid room number detected on file line: "
+ (i + 1), "Invalid Room Number", JOptionPane.WARNING_MESSAGE);
continue;
}
// Convert the current data line room number to Integer
int roomNum = Integer.parseInt(roomData[0]);
// Does the current data line room number equal the supplied
// room number?
if (roomNum != roomNumber) {
// If not then move on...
continue;
}
// If we reach this point then we know that we are currently on
// the the data line we need and want to make changes to.
String strg = ""; // Use for building a modified data line.
// Iterate through the current data line fields
for (int j = 0; j < roomData.length; j++) {
// If we reach the supplied field number to modify
// then we apply that modification to the field.
if (j == fieldToModify) {
roomData[j] = newFieldValue;
}
// Build the new data line. We use a Ternary Operator, it is
// basicaly the same as using a IF/ELSE.
strg += strg.equals("") ? roomData[j] : "|" + roomData[j];
}
// Replace the current List element with the modified data.
dataList.set(i, strg);
}
// Rewrite the Data File.
// Try with resources so as to auto close the FileWriter.
try (FileWriter writer = new FileWriter(filePath)) {
// Iterate through the List and write it to the data file.
// This ultimately overwrites the data file.
for (int i = 0; i < dataList.size(); i++) {
writer.write(dataList.get(i) + System.lineSeparator());
}
}
// Since no exceptions have been caught at this point return true
// for success.
return true;
}
catch (FileNotFoundException ex) {
Logger.getLogger("updateFileRoomStatus()").log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger("updateFileRoomStatus()").log(Level.SEVERE, null, ex);
}
// We must of hit an exception if we got
// here so return false for failure.
return false;
}
在上面的代码中,提供了数据文件名“HotelRoomsData.txt”。当然,这假定数据文件包含该名称,并且该名称位于特定项目的根文件夹(目录)中。如果文件的名称不同,并且位于完全不同的位置,则需要将其更改为数据文件的完整路径和文件名,例如:
"C:/Users/Documents/MyDataFile.txt"
代码并没有那么长,只是有很多注释伴随着它来解释事情。当然,这些注释可以从代码中删除。因此,您要将false更改为true的文件中有这些注释?@DevilsHnd Yes。现在为false,但当我删除文件室时,我想将其更改为truefile@rohitthomas我试过了,但不知怎么的,它只是在文本文件中写了新行。@NeoCortex试一下,这样它就在文件中了,你想将false改为true吗?@DevilsHnd是的。现在为false,但当我删除文件室时,我想将其更改为truefile@rohitthomas我试过了,但不知怎么的,它只是在文本文件中写了新行。@NeoCortex试试这个