【java基础:FileOutputStream】创建txt文件,写入中文内容

要求:

FileOutputStream创建流对象,在当前项目下创建a.txt文件,并写入内容,要求是中文。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class test {
    public static void main(String[] args) {
        //FileOutputStream对象写在try外面,以便在finally资源释放
        FileOutputStream fos = null;
        try {
            //FileOutputStream下方出现红线时,鼠标悬停后,选择提示,添加try...catch...
            fos = new FileOutputStream(new File("a.txt"));
            //fos.write下方出现红线时,鼠标悬停后,选择提示,添加catch
           byte[] bytes = "文件中写入中文".getBytes();
           fos.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //close下方出现红线,鼠标悬浮,选择提示,添加try...catch
            try {
                //close资源释放,不占用资源
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:

 总结:FileOutputStream创建txt文件时,写入中文,要把字符串转换成字节数组,即

 byte[] bytes = "文件中写入中文".getBytes();

中文即可在txt文件中显示。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
A: 以下是用Java实现往xlsx文件写入内容的示例代码: ``` import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class WriteExcel { public static void main(String[] args) { try { // 创建工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 创建表格 Sheet sheet = workbook.createSheet(); // 创建第一行,并设置值 Row row1 = sheet.createRow(0); Cell cell11 = row1.createCell(0); cell11.setCellValue("姓名"); Cell cell12 = row1.createCell(1); cell12.setCellValue("年龄"); // 创建第二行,并设置值 Row row2 = sheet.createRow(1); Cell cell21 = row2.createCell(0); cell21.setCellValue("张三"); Cell cell22 = row2.createCell(1); cell22.setCellValue(20); // 创建第三行,并设置值 Row row3 = sheet.createRow(2); Cell cell31 = row3.createCell(0); cell31.setCellValue("李四"); Cell cell32 = row3.createCell(1); cell32.setCellValue(25); // 将工作簿写入文件 FileOutputStream fos = new FileOutputStream("test.xlsx"); workbook.write(fos); fos.close(); System.out.println("写入成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 首先,需要导入Apache POI库,该库是用于操作Microsoft Office格式文件的开源Java库。 在代码中,我们首先创建了一个XSSFWorkbook对象,在该对象上创建一个Sheet对象,表示要操作的表格。 接着,我们创建了第一行和第二行,并在单元格中设置了值“姓名”和“年龄”、“张三”和“20”。 最后,我们将工作簿写入文件中,并在控制台输出写入成功的提示。 以上代码可以在Java SE 1.7及以上版本中运行,需要注意的是必须导入Apache POI的相关库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值