Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我可以在屏幕上打印F,但不能在Java中打印文件?_Java - Fatal编程技术网

为什么我可以在屏幕上打印F,但不能在Java中打印文件?

为什么我可以在屏幕上打印F,但不能在Java中打印文件?,java,Java,我编写了一个将字符串打印到外部文件的方法,但是在printf方法上出现了一个编译器错误。我使用了另一种方法将相同的字符串打印到屏幕上,唯一的区别是文件声明和用outFile.printf替换System.out.printf;这种方法没有错误。此方法中的错误是什么,如何修复 public static void printFile(String master) { File outFile = new File("output-file.txt"); /* code that d

我编写了一个将字符串打印到外部文件的方法,但是在printf方法上出现了一个编译器错误。我使用了另一种方法将相同的字符串打印到屏幕上,唯一的区别是文件声明和用outFile.printf替换System.out.printf;这种方法没有错误。此方法中的错误是什么,如何修复

public static void printFile(String master)
{
    File outFile = new File("output-file.txt");
    /* code that divides the string into tokens and assigns them to 
    variables name, diameter, mass, and gravity */
    outFile.printf("%n%-10s%10s%10s%10s", name, diameter, mass, gravity);
}

文件
没有
printf
方法-但是您可以从文件创建:

PrintStream ps = new PrintStream(outFile);
ps.printf("%n%-10s%10s%10s%10s", name, diameter, mass, gravity);

请注意,在使用完打印流后,您需要关闭它,最好指定编码。

您说您遇到了编译器错误。错误具体说明了什么?
printf
不是
文件的函数。应关闭PrintStream。。使用
try(PrintStream ps=…){ps.printf(…)}