0

I tried the method posted below but still no success. I get an error of cannot find symbol. How else can i modify the code below. Do i have to place the line in the bottom?

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);
    }

  }
}
Needyboy
  • 41
  • 9

3 Answers3

3

I would use Files.readAllLines(Path) like

String[] lines = Files.readAllLines(new File("haikuFun.txt").toPath());
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Simple one line solution using Java 8

String[] lines = Files.lines(Paths.get("somefile.txt")).toArray(String[]::new);
Jaspreet Jolly
  • 1,235
  • 11
  • 26
0

I would use Files.readAllLines(Path) like

String[] lines = Files.readAllLines(Paths.get("haikuFun.txt"));

But in case you have a huge file, you could have a problem. In this case, you could use Stream:

try (Stream<String> stream = Files.lines(Paths.get("haikuFun.txt"))) {
    stream.forEach(line -> System.out.println(line));
} catch(IOException e) {
    e.printStackTrace();
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35