[英]Java: PrintWriter object not detected
I am having some trouble getting java to recognize my PrintWriter object 'out'. 我在让java识别我的PrintWriter对象'out'时遇到了一些麻烦。 I'm not really sure what the problem is. 我不确定问题是什么。
public void storeInput(String fileName)
{
String folderName = "C:/temper/testy/";
File filetest = new File(folderName, fileName);
System.out.println("ENTER TEXT!!!!!");
String input = sc.nextLine();
try {
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(filetest)));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(filetest);
out.close();
}
declare that outside of try
宣布在try
之外
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter(filetest)));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The out
variable's scope is currently only in the scope of the try
block. out
变量的范围目前仅在try
块的范围内。 Declare it before the try
block so it's available after the block ends. 在try
块之前声明它,以便在块结束后可用。
You'll need to initialize it to null
so you don't get a "variable may not have been initialized" error. 您需要将其初始化为null
这样您就不会得到“变量可能尚未初始化”错误。 Then you'll need to test if it's null
when attempting to use it past the try
block. 然后,当尝试通过try
块使用它时,你需要测试它是否为null
。
PrintWriter out
is visible only inside the try
block. PrintWriter out
仅在try
块内可见。 accessing it from outside will result in a compile error. 从外部访问它将导致编译错误。
You can either move it's declaration outside the try
block so that it become in you case visible in the hole body of the function storeInput
but then you'll have to check whether ist is initialized before the statments 你可以在try
块之外移动它的声明,这样它就可以在函数storeInput
的漏洞体中看到,但是你必须检查是否在声明之前初始化了ist
out.println(filetest);
out.close();
or better you move those tow statements in side the try
block so when no exception accours out
is always initialized. 或者你更好地将那些两个语句移动到try
块的一侧,这样当没有异常累积out
总是被初始化。
For the close
it is better to place it inside a finally
block, that way you are always releasing resources no matter what exception happens. close
它最好将它放在finally
块中,这样无论发生什么异常,你总是释放资源。
public void storeInput(String fileName)
{
String folderName = "C:/temper/testy/";
File filetest = new File(folderName, fileName);
System.out.println("ENTER TEXT!!!!!");
String input = sc.nextLine();
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter(filetest)));
out.println(filetest);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(out != null) {
out.close();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.