Java 带循环检查的文件输出,并尝试catch块
在文件输出和使用try/catch时遇到一些问题。我想说的是,如果用户输入了一个现有的文件名,那么继续循环直到输入了有效的文件名。然而,我似乎无法让它发挥作用。有什么关于我哪里出错的提示吗?尝试在try块周围移动初始提示,但这不会使作用域仅在try块中可用吗?因此,本质上,我应该让提示符在外部,以便它可用于所有try/catch块?不过我不确定Java 带循环检查的文件输出,并尝试catch块,java,while-loop,try-catch,fileoutputstream,Java,While Loop,Try Catch,Fileoutputstream,在文件输出和使用try/catch时遇到一些问题。我想说的是,如果用户输入了一个现有的文件名,那么继续循环直到输入了有效的文件名。然而,我似乎无法让它发挥作用。有什么关于我哪里出错的提示吗?尝试在try块周围移动初始提示,但这不会使作用域仅在try块中可用吗?因此,本质上,我应该让提示符在外部,以便它可用于所有try/catch块?不过我不确定 import java.util.Scanner; import java.io.File; import java.io.IOExcepti
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class TestAccountWithException
{
public static void main(String[] args) throws IOException
{
// variable declaration
String fileName;
String firstName;
String lastName;
double balance;
int id = 1122;
final double RATE = 4.50;
Scanner input = new Scanner(System.in);
System.out.print("Please enter file name: ");
fileName = input.next();
File fw = new File(fileName);
try
{
// check if file already exists
while(fw.exists())
{
System.out.print("File already exists. Enter valid file name: ");
fileName = input.next();
fw = new File(fileName);
}
System.out.print("Enter your first name: ");
firstName = input.next();
System.out.print("Enter your last name: ");
lastName = input.next();
System.out.print("Input beginnning balance: ");
balance = input.nextDouble();
// pass object to printwriter and use pw to write to the file
PrintWriter pw = new PrintWriter(fw);
// print to created file
pw.println(firstName);
pw.println(lastName);
pw.println(balance);
pw.println(id);
pw.println(RATE);
pw.close();
// System.out.print("Run program? (1) Yes (2) No: ");
// cont = input.nextInt();
} catch (IOException e) {
e.printStackTrace();
}
} // end main
} // end class
您可能更喜欢使用
java.nio.file
。有了这个Java7包,您可以使用
while(true) {
String fileName = input.next();
Path path = Paths.get(fileName);
if (Files.exists(path)) {
try {
// file exists
// your operations
} catch {
}
break;
} else {
// not found
fileName = input.next();
}
}
@javaaaaaa您的代码正在运行,您可以指定是否有任何错误。