java - 写入字体文件
问题描述
我需要创建一个方法,给定文件名和整数 n 写入具有该名称的字符文件,n 个随机整数,每行一个。这是我的代码,我认为它编写正确,但我传递的文件仍然是“空”的,大小为 0 字节。有人能帮我吗?
public static void scriviIntero(String nomeFile, int n) {
try (PrintWriter scrivi = new PrintWriter(new FileWriter(nomeFile, true))) {
Random random = new Random();
for (int i = 0; i < n; i++) {
int nuovo = random.nextInt(99999);
scrivi.println(nuovo);
}
} catch (IOException e) {
System.out.println("Errore di I/O nella funzione scriviIntero nel tentativo di scrivere sul file " + nomeFile);
}
}
解决方案
你的问题是不正确的初始化FileWriter
。看看我放的地方true
:
public static void main(String[] args) throws IOException {
appendRandomNumbersToFile("e:/foo.txt", 10);
appendRandomNumbersToFile("e:/foo.txt", 20);
}
public static void appendRandomNumbersToFile(String fileName, int n) throws IOException {
if (n <= 0)
throw new RuntimeException("n should be positive");
try (PrintWriter writer = new PrintWriter(new FileWriter(fileName, true))) {
Random random = new Random();
for (int i = 0; i < n; i++)
writer.println(random.nextInt());
}
}
PS这是来自JavaDoc:
public FileWriter(String fileName, boolean append) {}
public PrintWriter(Writer out, boolean autoFlush) {}
推荐阅读
- linux - 使用第一阶段的文件夹构建 docker 多阶段
- python-3.x - AirFlow 正在触发具有先前有效运行日期的 DAG
- jenkins - 多行 groovy Jenkinsfile 中的 sh 命令
- gcc - 如何在不删除 libgtk2-dev:armhf 的情况下安装 libgtk2-dev:i386?或者如何为 i386 和 armhf 进行交叉编译?
- c# - 如何获取oid类型OctetString的值
- perl - 在 Perl 中使用三元条件运算符有更短的方法吗?
- php - 使用 php 将文件上传到 Dropbox - Dropbox-SDK-PHP
- android - 如果我登录另一个用户而不注销前一个用户会发生什么?
- ios - 可以将数据从应用程序传输到浏览器
- python-3.x - Sympy:空图作为输出