我需要将一堆字符串打印到文件中,但是我似乎在犯一些错误。没有错误消息,并且如果我在while循环中放入普通的print语句;它打印那些。它只是不将其打印到文件中。程序的另一部分读取另一个文件,并在该行中添加一行以写入文件。
代码:
public static void writeToFile (String a, String username) throws FileNotFoundException {
Scanner lineScan = new Scanner (a);
String name = lineScan.next();
PrintStream newFile = new PrintStream (new File (username+".txt"));
//The below newFile command works
newFile.println(username);
if ((username.toUpperCase()).equals(name.toUpperCase()))
{
int count = 0;
while (lineScan.hasNextInt())
{
int pop = lineScan.nextInt();
String s1 = 1920 + (10*count) + ": " + pop;
newFile.println(s1);
count++;
}
newFile.close();
}
}
答案 0 :(得分:0)
您可以尝试以下方法:
public static void writeToFile (String a, String username) throws FileNotFoundException {
Scanner lineScan = new Scanner (a);
String name = lineScan.next();
PrintStream newFile = new PrintStream (new File (username+".txt"));
//The below newFile command works
newFile.println(username);
if ((username.toUpperCase()).equals(name.toUpperCase()))
{
int count = 0;
System.setOut(newFile);
while (lineScan.hasNextLine())
{
String pop = lineScan.nextLine();
String s1 = 1920 + (10*count) + ": " + pop;
System.out.println(s1);
count++;
}
newFile.close();
}
}
答案 1 :(得分:0)
我看不到flush()/close()
在任何地方(if块之外)都被调用。
flush()/ close(),以实际执行对基础输出Stream(对于您的情况为File)的写操作。
答案 2 :(得分:0)
问题是您正在读取文件名的文本,而不是文件本身,要使用Scanner类读取文件,可以像在PrintStream中那样使用文件对象。
固定代码:
public static void writeToFile (String a, String username) throws FileNotFoundException {
Scanner lineScan = new Scanner (new File(a));
String name = lineScan.next();
PrintStream newFile = new PrintStream (new File (username+".txt"));
//The below newFile command works
newFile.println(username);
if ((username.toUpperCase()).equals(name.toUpperCase()))
{
int count = 0;
while (lineScan.hasNextInt())
{
int pop = lineScan.nextInt();
String s1 = 1920 + (10*count) + ": " + pop;
newFile.println(s1);
count++;
}
}
newFile.close();
lineScan.close();
}