到目前为止我写了这篇文章,我只是从我的教科书中做了一些练习代码。我似乎无法阅读我的.txt中的第一行。
/**
*
*/
import java.util.Scanner; //needed for scanner class
import java.io.*; //needed for File I/O classes
/**
* @author Megan
*
*/
public class Pres {
/**
* @param args
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of file: C:/User/Frances/Documents/USPres.txt");
String filename = keyboard.nextLine();
File file = new File("C:/User/Frances/Documents/USPres.txt");
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
System.out.println("The first line in the file is: ");
System.out.println(line);
inputFile.close();
}
}
我认为这与代码的这一部分有关:
String line = inputFile.nextLine();
我不太确定要在()中键入什么,如果我应该输入任何东西。我错了。我的教科书没有清楚正确的格式。如果你能提供帮助,请谢谢。 :)
答案 0 :(得分:0)
要读取txt文件,请执行以下操作:
String line = "";
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(fileName));
while ((line = in.readLine()) != null) {
// do something here
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
它将读取文本中的所有行,但由于它的练习继续进行并尝试弄清楚如何只阅读一行。
答案 1 :(得分:0)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Pres {
public static void main(String[] args) throws FileNotFoundException, IOException {
// BufferedReader is best for read line from file or else
BufferedReader Bfr = new BufferedReader(new FileReader("your_filename_or_path.txt"));
// get first line from file
String firstLinetext = Bfr .readLine();
System.out.println(firstLinetext ); // print first line
}
}