[英]Reading from text files
我需要使用Java从文本文件中读取数据,目前正在使用:
public void read() throws Exception
{
FileInputStream in = null;
try
{
Scanner input = new Scanner("dataset.txt");
File inputFile = new File(fileName.nextLine());
in = new FileInputStream(inputFile);
}
catch ( Exception e)
{
System.out.println(e);
}
}
但是,我希望给用户一个选择读取dataset.txt和data.txt的选择,因此我尝试这样做:
public void read(int name) throws Exception
{
FileInputStream in = null;
try
{
File inpu = new File(name.nextLine());
in = new FileInputStream(input);
}
catch ( Exception e)
{
System.out.println(e);
}
但我遇到一个错误:不能取消引用int
fileName
类型为int
。 您不能从原始类型调用方法。
由于只有两个不同的文件,所以为什么不使用if
语句查看用户要打开的文件,然后将该文件提供给inputFile
,您可以将其传递给in
。
if (fileName == 1) {
inputFile = new File("dataset.txt");
} else if (fileName == 2) {
inputFile = new File("data.txt");
}
如果“名称”输入变量是用户选择的值,则需要根据用户的决定使用条件来选择相应的文件名
例:
public void read(int name) throws Exception {
FileInputStream in = null;
try {
// File selection depending on user number selection
String fileName="dataSet.txt";
if(name == 2){
fileName ="otherFileName.txt";
}
// InputStream creation
File input = new File(fileName);
in = new FileInputStream(input);
// Your read operations here
} catch ( Exception e) {
System.out.println(e);
}
}
在此示例中,如果用户按2,则使用“ otherFileName.txt”。 否则,将使用“ dataSet.txt”。
所有文件也没有路径。 这些意味着必须位于应用程序的启动路径中。
首先,您的代码有很多错误。 我想如果您在控制台上显示此行
System.out.print("Please choose a dataset (1) dataset.txt , (2)data.txt : ");
用户的输入为int
并且您像fileName.nextLine()
这样传递,这会导致错误
尝试这个:
Scanner scan=new Scanner(System.in));
fileName="";
System.out.print("Please choose a dataset (1) dataset.txt , (2)data.txt : ");
int input = scan.nextInt();
if(input==1){
fileName="dataset.txt";
}
if(input==2){
fileName="data.txt";
}
File inputFile=new File(fileName));
... .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.