能不能写一段导入导出的java代码
时间: 2023-05-25 19:03:57 浏览: 123
当你说“导入导出”时,这可能涉及许多不同的场景和格式。以下是一个通用的Java代码示例,用于将数据导出为CSV文件并从CSV文件中导入数据。
```java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ImportExportExample {
public static void main(String[] args) {
String filePath = "data.csv";
// 导出数据到CSV文件
List<String[]> data = new ArrayList<>();
data.add(new String[] {"John", "Doe", "40"});
data.add(new String[] {"Jane", "Smith", "35"});
data.add(new String[] {"Bob", "Johnson", "45"});
exportToCsv(filePath, data);
// 从CSV文件导入数据
List<String[]> importedData = importFromCsv(filePath);
for (String[] row : importedData) {
System.out.println(row[0] + " " + row[1] + ", age " + row[2]);
}
}
// 导出数据到CSV文件
public static void exportToCsv(String filePath, List<String[]> data) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (String[] row : data) {
writer.write(String.join(",", row));
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 从CSV文件导入数据
public static List<String[]> importFromCsv(String filePath) {
List<String[]> data = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
data.add(row);
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
```
以上代码中的 `exportToCsv` 方法将一个包含字符串数组的列表写入到CSV文件中。每个字符串数组都表示CSV文件中的一行,每个元素用逗号分隔。在该方法中,我们使用 `BufferedWriter` 和 `FileWriter` 将数据写入磁盘文件。
`importFromCsv` 方法根据文件路径读取CSV文件并返回一个包含所有行的字符串数组列表。在该方法中,我们使用 `BufferedReader` 和 `FileReader` 从磁盘文件中读取数据。
请注意,以上代码仅用于演示目的。在实际情况中,您可能需要加入更多的错误处理和格式验证逻辑以确保数据及其格式是正确的。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)