1

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.

Reporter
  • 3,897
  • 5
  • 33
  • 47
Rincewind
  • 412
  • 1
  • 10
  • 26
  • The readline seems to be in order, but in OpenFile the numberOfLines = 0; will guarrantee it won't read anything... – ppeterka Sep 09 '13 at 14:16
  • @ppeterka 66 The reason that I defined 'int numberOfLines = 0;' is because NetBeans wouldn't allow to create an object without establishing an initial parameter. I wanted numberOfLines to reference the object within the OpenFiles method by using the for loop. Is there any way that I can do that? That way, it keeps it simple. – Rincewind Sep 09 '13 at 15:46
  • Well, if you would create an instance variable in the ReadFiles class, and use that to store the number of lines, this could work. However, having an object storing a file name and the lines of the file seems odd. The file can change, and the number of lines gets out of syns. – ppeterka Sep 09 '13 at 18:42
  • @ppeterka66 I considered making an instance variable but I couldn't do a 'close();' object with a field variable to clear out the memory to use it again (I think). I wanted the object numberOfLines to reference a method that can dynamically count the number of lines in a text, return the int to the method that reads the text (BufferedReader) and then I can render the information from the BufferedReader into a String array. Would that be the cleanest way to do that? I believe there is beauty in simplicity. – Rincewind Sep 09 '13 at 21:19
  • Check out my other post: [link](http://stackoverflow.com/questions/20937369/bufferreader-to-write-new-file-with-previous-info/20937551#20937551) –  Jan 06 '14 at 05:14

3 Answers3

2

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
 }
}
ppeterka
  • 20,583
  • 6
  • 63
  • 78
  • This one did it for me. Also, the fact that you manipulated the data output from an Array to a String really helped to learn data manipulation. Thanks! – Rincewind Sep 23 '13 at 20:20
0
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.

Ahmed KRAIEM
  • 10,267
  • 4
  • 30
  • 33
0

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.

mwjohnson
  • 661
  • 14
  • 26