如何从txt文件中读取以下信息,并使用Java将数字写入另一个文本文件?我把它显示到控制台但它也不会写入文件。
Jones 369218658389641
史密斯6011781008881301
Wayne 5551066751345482
葡萄酒4809134775860430
Biggie 9925689541232325
卢克7586425896325410
白兰地4388576018410707
瑞安2458912425860439
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called cardnums.txt
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
}
}
我现在知道了。
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called credit.txt
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
output.flush();
output.close();
}
}
答案 0 :(得分:1)
java.io.PrintWriter output = new java.io.PrintWriter(file);
首先,为什么你每次都使用相同的文件名调用此循环?
其次,一旦你在循环外定义它,
在outputstream对象上调用flush()并在循环后关闭if if(最好在finally块中)。
if(output!=null) {
output.flush();
output.close();
}
答案 1 :(得分:0)
这是一个单行:
Files.write(Paths.get("cardnums.txt"), () ->
Files.lines(Paths.get("accounts.txt"))
.map(s -> s.replaceAll("\\D", ""))
.collect(toList())
.iterator());
免责声明:代码可能无法编译或工作,因为它在我的手机上被翻阅(但它有合理的可能性)