-1

I don't understand why this code won't read a .txt file then convert it to an array. I don't have the exact number of rows to begin with (to set the array) so I count the .txt files rows with a while loop. This program should count the number of rows it imports then create a new array to copy & print the information to the console.

public class Cre{

    public void openFile() throws IOException{

BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\file.txt"));
String line = in.readLine();
int i=0;

String linecounterguy = "null";
int count = 0;
while(line!= null) { ///to count number of rows///

    linecounterguy = in.readLine();
    count += 1;
}

String[] array = new String[count+1];
String line1 = "try";
while(line!= null)
{
  line1 = in.readLine();
  System.out.println(line1); 



}
in.close();
for (int j = 0; j < array.length-1 ; j++) {
    linecounterguy = in.readLine();
        System.out.println(array[j]);

    }
    }
}

Main Class

> public class JavaApplication8 {
> 
>     /**
>      * @param args the command line arguments
>      */
>     public static void main(String[] args) throws IOException {
>         
>         
>         Cre k = new Cre();
>         k.openFile();
>     
>     
>     } }
Javaing
  • 47
  • 6
  • Possible duplicate of [read lines in txt file \[java\]](http://stackoverflow.com/questions/4315227/read-lines-in-txt-file-java) – jiaweizhang Dec 11 '15 at 00:59

1 Answers1

0

Here is a little method that will get you started with reading a text file into an array of strings. Hope this helps!

public String[] readLines(String filename) throws IOException {
    FileReader fileReader = new FileReader(filename);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    List<String> lines = new ArrayList<String>();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
    }
    bufferedReader.close();
    return lines.toArray(new String[lines.size()]);
}
fergdev
  • 963
  • 1
  • 13
  • 27