java边读边写

该博客展示了如何在Java中实现从标准输入流读取数据并同时将其写入文本文件的操作。通过使用InputStreamReader、BufferedReader、FileWriter和BufferedWriter,程序实现了边读取用户输入(直到输入'quit')边将内容追加到指定的文本文件中。
摘要由CSDN通过智能技术生成


public class Main {
public static void main(String[] args) throws IOException {
// 将inputstream转换成字符流
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
//
BufferedReader reader = new BufferedReader(inputStreamReader);
File file = new File("D:\\A.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
String line;
while (!(line = reader.readLine()).equals("quit")) {
Java中,使用`Workbook`边读通常是指在处理Excel文件时,需要对某些数据进行读取并根据数据的处理结果进行操作。Apache POI库提供了一种方便的方式来进行这种操作。以下是一个使用Apache POI的示例代码,演示如何边读: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ExcelReadWriteExample { public static void main(String[] args) { String excelFilePath = "example.xlsx"; // 指定Excel文件路径 try (FileInputStream inputStream = new FileInputStream(excelFilePath); Workbook workbook = new XSSFWorkbook(inputStream)) { Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 // 遍历行 for (Row row : sheet) { // 遍历列 for (Cell cell : row) { // 读取单元格中的值 String cellValue = cell.getStringCellValue(); // 根据需要对cellValue进行处理 // ... // 假设处理后的新值为newValue String newValue = cellValue + "_processed"; // 创建新的单元格样式 CellStyle newCellStyle = workbook.createCellStyle(); // 可以设置新样式,例如字体、边框等 // 将新值入单元格 Cell newCell = row.createCell(cell.getColumnIndex(), CellType.STRING); newCell.setCellValue(newValue); newCell.setCellStyle(newCellStyle); } } // 入操作完成后,需要将Workbook回文件 try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) { workbook.write(outputStream); } } catch (IOException e) { e.printStackTrace(); } } } ``` 这个例子中,我们首先使用`FileInputStream`读取了一个存在的Excel文件,并用`XSSFWorkbook`创建了对应的`Workbook`对象。然后通过遍历工作表的行和列,读取单元格的值,并对这些值进行处理。处理后的值被入新的单元格中,然后我们使用`FileOutputStream`将修改后的`Workbook`对象回原文件。 注意:如果在处理过程中需要保持原有格式,可以考虑复制原单元格的样式。同时,如果要保存的文件和原文件是同一个,需要在入之前关闭输入流。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值