Java文件处理与集合类应用指南
立即解锁
发布时间: 2025-08-20 00:52:11 订阅数: 11 


Java网络编程入门与实践
### Java文件处理与集合类应用指南
#### 1. 带GUI的文件输入输出
如今,大多数应用程序都具备图形用户界面(GUI),为文件处理程序提供这样的界面是很有必要的。通过使用Swing类`JFileChooser`,我们可以显示一个对话框,让用户浏览计算机的文件系统,并选择要打开的现有文件或要创建文件的目标目录。
##### 1.1 `JFileChooser`的使用
- **创建对象**:`JFileChooser`对象会打开一个模态对话框,显示系统的目录结构,允许用户进行遍历。
```java
JFileChooser fileChooser = new JFileChooser();
```
- **设置文件选择模式**:使用`setFileSelectionMode`方法指定用户可选择的是文件、目录还是两者皆可。
```java
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
```
可用的常量有:
- `JFileChooser.FILES_ONLY`:仅选择文件
- `JFileChooser.DIRECTORIES_ONLY`:仅选择目录
- `JFileChooser.FILES_AND_DIRECTORIES`:文件和目录均可选择
- **显示对话框**:可以调用`showOpenDialog`或`showSaveDialog`方法。前者显示带有“Open”和“Cancel”按钮的对话框,后者显示带有“Save”和“Cancel”按钮的对话框。
```java
int selection = fileChooser.showOpenDialog(null);
```
如果传入`null`作为参数,对话框将显示在屏幕中央。
- **处理选择结果**:返回的整数值可以与以下常量进行比较:
- `JFileChooser.CANCEL_OPTION`:用户取消选择
- `JFileChooser.APPROVE_OPTION`:用户选择了文件
```java
if (selection == JFileChooser.APPROVE_OPTION) {
// 处理文件选择后的操作
}
```
- **获取所选文件**:如果用户选择了文件,可以使用`getSelectedFile`方法获取对应的`File`对象。
```java
File file = fileChooser.getSelectedFile();
```
##### 1.2 文件的序列化输入输出
- **字符串和基本类型的序列化**:可以使用`Scanner`对象进行输入,使用`PrintWriter`对象进行输出。
```java
Scanner fileIn = new Scanner(file);
PrintWriter fileOut = new PrintWriter(file);
```
可以使用`next`、`nextInt`等方法进行输入,使用`print`和`println`方法进行输出。
- **对象的序列化**:使用`ObjectInputStream`和`FileInputStream`对象进行输入,使用`ObjectOutputStream`和`FileOutputStream`对象进行输出。
```java
ObjectInputStream fileIn = new ObjectInputStream(new FileInputStream(file));
ObjectOutputStream fileOut = new ObjectOutputStream(new FileOutputStream(file));
```
可以使用`readObject`和`writeObject`方法进行对象的读写。
##### 1.3 示例代码
以下是一个简单的应用程序,用于读取考试成绩文件并逐个显示学生的成绩。
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class UseFileChooser extends JFrame implements ActionListener {
private JPanel displayPanel, buttonPanel;
private JLabel surnameLabel, firstNamesLabel, markLabel;
private JTextField surnameBox, firstNamesBox, markBox;
private JButton openButton, nextButton;
private Scanner input;
public static void main(String[] args) {
UseFileChooser frame = new UseFileChooser();
frame.setSize(350, 150);
frame.setVisible(true);
}
public UseFileChooser() {
setTitle("FileChooser Demo");
setLayout(new BorderLayout());
displayPanel = new JPanel();
displayPanel.setLayout(new GridLayout(3, 2));
surnameLabel = new JLabel("Surname");
firstNamesLabel = new JLabel("First names");
markLabel = new JLabel("Mark");
surnameBox = new JTextField();
firstNamesBox = new JTextField();
markBox = new JTextField();
surnameBox.setEditable(false);
firstNamesBox.setEditable(false);
markBox.setEditable(false);
displayPanel.add(surnameLabel);
displayPanel.add(surnameBox);
displayPanel.add(firstNamesLabel);
displayPanel.add(firstNamesBox);
displayPanel.add(markLabel);
displayPanel.add(markBox);
add(displayPanel, BorderLayout.NORTH);
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
openButton = new JButton("Open File");
openButton.addActionListener(this);
nextButton = new JButton("Next Record");
nextButton.addActionListener(this);
nextButton.setEnabled(false);
buttonPanel.add(openButton);
buttonPanel.add(nextButton);
add(buttonPanel, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
if (input != null) {
input.close();
}
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == openButton) {
try {
openFile();
} catch (IOException ioEx) {
JOptionPane.showMessageDialog(this, "Unable to open file!");
}
} else {
try {
readRecord();
} catch (EOFException eofEx) {
nextButton.setEnabled(false);
JOptionPane.showMessageDialog(this, "Incomplete record!\nEnd of file reached.");
} catch (IOException ioEx) {
JOptionPane.showMessageDialog(this, "Unable to read file!");
}
}
}
public void openFile() throws IOException {
if (input != null) {
input.close();
input = null;
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int selection = fileChooser.showOpenDialog(null);
if (selection == JFileChooser.CANCEL_OPTION) {
return;
}
File results = fileChooser.getSelectedFile();
if (results == null || results.getName().equals("")) {
JOptionPane.showMessageDialog(this, "Invalid selection!");
return;
}
input = new Scanner(results);
readRecord();
nextButton.setEnabled(true);
}
public void readRecord() throws IOException {
String surname, firstNames, textMark;
surnameBox.setText("");
firstNamesBox.setText("");
markBox.setText("");
if (input.hasNext()) {
surname = input.nextLine();
surnameBox.setText(surname);
} else {
JOptionPane.showMessageDialog(this, "End of file reached.");
nextButton.setEnabled(false);
return;
}
if (!input.hasNext()) {
throw (new EOFException());
}
firstNames = input.nextLine();
firstNamesBox.setText(firstNames);
if (!input.hasNext()) {
throw (new EOFException());
}
textMark = input.nextLine();
markBox.setText(textMark);
}
}
```
#### 2. `ArrayList`的使用
`ArrayList`是一种类似于数组的对象,但可以根据应用程序的存储需求动态增加或减少大小,并且只能存储对象的引用,不能存储基本类型的值。
##### 2.1 `ArrayList`的创建
- **完整语法**:
```java
ArrayList<String> stringArray = new ArrayList<String>();
```
- **简化语法(Java SE 7及以上)**:
```java
ArrayList<String> nameList = new ArrayList<>();
```
##### 2.2 对象的添加和获取
- **添加对象**:使用`add`方法将对象添加到`ArrayList`的末尾。
```java
String name1 = "Jones";
nameList.add(name1);
```
- **获取对象**:使用`get`方法根据索引获取对象。
```java
String name2 = nameList.get(0);
```
- **在指定位置添加对象**:可以使用重载的`add`方法在指定位置添加对象。
```java
nameList.add(2, "Patterson");
```
#### 3. `ArrayList`的序列化
将一系列对象放入一个`ArrayList`中并保存到磁盘比保存单个对象更高效,并且可以通过`ArrayList`的`get`方法进行随机访问。
##### 3.1 示例代码
```java
import java.io.*;
import java.util.*;
public class ArrayListSerialise {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectOutputStream outStream = new ObjectOutputStream(new FileOutputStream("personnelList.dat"));
ArrayList<Personnel> staffListOut = new ArrayList<>();
ArrayList<Personnel> staffListIn = new ArrayList<>();
Personnel[] staff = {
new Personnel(123456, "Smith", "John"),
new Personnel(234567, "Jones", "Sally Ann"),
new Personnel(999999, "Black", "James Paul")
};
for (int i = 0; i < staff.length; i++) {
staffListOut.add(staff[i]);
}
outStream.writeObject(staffListOut);
outStream.close();
ObjectInputStream inStream = new ObjectInputStream(new FileInputStream("personnelList.dat"));
int staffCount = 0;
try {
staffListIn = (ArrayList<Personnel>) inStream.readObject();
for (Personnel person : staffListIn) {
staffCount++;
System.out.println("\nStaff member "
```
0
0
复制全文
相关推荐










