亲爱的,我有这个代码:
File file = new File("flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
String line = in.nextLine();
System.out.println(line);
我想从一个文件中读取并打印每一行,但是由于一些例外(抛出异常??),这段代码不起作用,我怎样才能以一种从flowers.txt中读取的方式放置它文件,在我的桌面上,将在控制台中打印此文件中的每一行?
答案 0 :(得分:1)
重新检查您的代码
File file = new File("flowers_petal.txt"); // This is not your desktop location.. You are probably getting FileNotFoundException. Put Absolute path of the file here..
while(in.hasNext()){ // checking if a "space" delimited String exists in the file
String line = in.nextLine(); // reading an entire line (of space delimited Strings)
System.out.println(line);
SideNote:使用FileReader + BufferedReader“读取”文件。使用Scanner解析文件..
答案 1 :(得分:0)
您正在检查错误的情况,您需要检查hasNextline()
而不是hasNext()
。所以循环将是
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
答案 2 :(得分:0)
考虑以下两点:
new Scanner(File file)
抛出FileNotFoundException
,因此您必须将代码放入try-catch
块或仅使用throws
。您的代码可能如下所示:
try {
File file = new File("path_to_Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e){
e.printStackTrace();
}
答案 3 :(得分:0)
试试这个
public static void main(String[] args) throws FileNotFoundException {
//If your java file is in the same directory as the text file
//then no need to specify the full path ,You can just write
//File file = new File("flowers_petal.txt");
File file = new File("/home/ashok/Desktop/flowers_petal.txt");
Scanner in = new Scanner(file);
while(in.hasNext()){
System.out.println(in.nextLine());
}
in.close();
}
注意:我正在使用Linux,如果您使用的是Windows,那么桌面路径会有所不同
答案 4 :(得分:0)
在这里你去..完整的代码示例。假设您将文件放在C:\ some_folder
中import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReader {
public static void main(String args[]) {
File file = new File("C:\\some_folder\\flowers_petal.txt");
Scanner in;
try {
in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
答案 5 :(得分:0)
试试这个................
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在FileReader中提供您的确切路径("确切路径必须在此处...")
来源:http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/