gpt4 book ai didi

Java - 复制到新的 txt 文件

转载 作者:行者123 更新时间:2023-11-29 05:21:36 24 4
gpt4 key购买 nike

这个程序创建的新 test1.txt 文件完全是空的,原始文件 test.txt 填充了类似“50 3 21 57 10 20”的东西,基本上是整数,它们之间有空格。

import java.util.*;
import java.io.*;

class AddOneToInts

{

public static void main(String [] args) throws IOException
{
Scanner scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
BufferedWriter writer = new BufferedWriter(new FileWriter( "text1.txt" ));
boolean cont = true;
String temp;

while (cont) {
if (scan.hasNextInt()) {
temp = (scan.nextInt()+1) + " ";
writer.write(temp);
} else break;
}
}
}

最佳答案

您必须关闭流以便 Java 将其内容刷新到文件中:

   Scanner scan = new Scanner(new BufferedReader(new FileReader( "test.txt" )));
BufferedWriter writer = new BufferedWriter(new FileWriter( "text1.txt" ));
boolean cont = true;
String temp;

while (cont) {
if (scan.hasNextInt()) {
temp = (scan.nextInt()+1) + " ";
writer.write(temp);
} else break;
}
writer.close(); // <<------------------------

关于Java - 复制到新的 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24477491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com