Code for reading from a text file doesn't work

3.4k views Asked by At

I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.

I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.

I have altered it a bit from what I was given. Here is where I am now:

This is my main class

package textfiles;

import java.io.IOException;

public class FileData {

public static void main(String[] args) throws IOException {

    String file_name = "C:/Users/Desktop/test.txt";


        ReadFile file = new ReadFile(file_name);
        String[] aryLines = file.OpenFile();
        int nLines = file.readLines();
        int i = 0;            

    for (i = 0; i < nLines; i++) {
        System.out.println(aryLines[i]);
      }
    }    
  }

This is my class that will read the text file and sense the number of lines

package textfiles;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

private String path;

public ReadFile(String file_path) {
    path = file_path;
}
int readLines() throws IOException {

  FileReader file_to_read = new FileReader(path);
  BufferedReader bf = new BufferedReader(file_to_read);

  int numberOfLines = 0;
  String aLine;

  while ((aLine = bf.readLine()) != null) {
  numberOfLines++;
}
bf.close();
return numberOfLines;
}

public String[] OpenFile() throws IOException {

  FileReader fr = new FileReader(path);
  BufferedReader textReader = new BufferedReader(fr);

  int numberOfLines = 0;

  String[] textData = new String[numberOfLines];

  int i;

 for (i = 0; i < numberOfLines; i++) {
    textData[i] = textReader.readLine();
  }

textReader.close();
return textData;
 }
}

Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.

3

There are 3 answers

1
ppeterka On BEST ANSWER

The problem is, you set the number of lines to read as zero with int numberOfLines = 0;

I'd rather suggest to use a list for the lines, and then convert it to an array.

public String[] OpenFile() throws IOException {

  FileReader fr = new FileReader(path);
  BufferedReader textReader = new BufferedReader(fr);

  //int numberOfLines = 0; //this is not needed

  List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file

  //this part should work akin to the readLines part
  String aLine;
  while ((aLine = bf.readLine()) != null) {
      textData.add(aLine); //add the line to the list
  }

  textReader.close();
  return textData.toArray(new String[textData.size()]); //convert it to an array, and return
 }
}
0
Ahmed KRAIEM On
int numberOfLines = 0;
String[] textData = new String[numberOfLines];

textData is an empty array. The following for loop wont do anything.

Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
   list.add(line);
}
br.close();

I also suggest that you read tutorials on object oriented concepts.

0
mwjohnson On

This is a class that I wrote awhile back that I think you may find helpful.

public class FileIO {
  static public String getContents(File aFile) {
    StringBuilder contents = new StringBuilder();
    try {
        //use buffering, reading one line at a time
        //FileReader always assumes default encoding is OK!
        BufferedReader input = new BufferedReader(new FileReader(aFile));
        try {
            String line = null; //not declared within while loop
            /*
             * readLine is a bit quirky :
             * it returns the content of a line MINUS the newline.
             * it returns null only for the END of the stream.
             * it returns an empty String if two newlines appear in a row.
             */
            while ((line = input.readLine()) != null) {
                contents.append(line);
                contents.append(System.getProperty("line.separator"));
            }
        } finally {
            input.close();
        }
    } catch (IOException ex) {
    }
    return contents.toString();
}

static public File OpenFile()
{
    return (FileIO.FileDialog("Open"));
}

static private File FileDialog(String buttonText) 
{
    String defaultDirectory = System.getProperty("user.dir");
    final JFileChooser jfc = new JFileChooser(defaultDirectory);
    jfc.setMultiSelectionEnabled(false);
    jfc.setApproveButtonText(buttonText);
    if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION) 
    {
        return (null);
    }
    File file = jfc.getSelectedFile();
    return (file);
}
}

It is used:

  File file = FileIO.OpenFile(); 

It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.