我尝试了以下发布的方法,但仍然没有成功。我收到找不到符号的错误。我还能如何修改下面的代码。我必须将线放在底部吗?
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
/**
* Write a description of class lab8 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class lab8
{
public static void main(String[] args) throws IOException
{
FileInputStream fileIn = new FileInputStream("haikuFun.txt");
Scanner scrn = new Scanner(fileIn);
String[] lines = fileIn.readAllLines(new File("haikuFun.txt").toPath());
while(scrn.hasNext()) {
String s = scrn.nextLine();
System.out.println(s);
}
}
}
答案 0 :(得分:3)
String[] lines = Files.readAllLines(new File("haikuFun.txt").toPath());
答案 1 :(得分:1)
使用Java 8的简单一线解决方案
String[] lines = Files.lines(Paths.get("somefile.txt")).toArray(String[]::new);
答案 2 :(得分:0)
String[] lines = Files.readAllLines(Paths.get("haikuFun.txt"));
但是,如果您的文件很大,可能会遇到问题。在这种情况下,您可以使用Stream:
try (Stream<String> stream = Files.lines(Paths.get("haikuFun.txt"))) {
stream.forEach(line -> System.out.println(line));
} catch(IOException e) {
e.printStackTrace();
}