0

I'm new at java I would like to know how to read a .txt file and then put every single line in an array cell. .txt file must be formatted as shown:

car //goes in array[0]
boat //goes in array[1]
ship //goes in array[2]
airplane //goes in array[3]
//...and so on..

I've already tried to create a ReadFile class implemented in this way:

import java.io.*;
import java.util.*;
public class ReadFile {
    private Scanner x;

public void open(){
    try{
        x = new Scanner(new File("time_table_data.txt"));
    }catch(Exception e){
        System.out.println("Could Not Create The File");
    }
}

public String read(){
    String s = "";
    while(x.hasNext()){
        String a = x.next();
        s = a.format("%s\n",a);
    }
    return s;
}


public void close(){
    x.close();
}


}
6
  • 2
    What exact problem are you facing? You forgot to ask a question. Questions normally end with question marks. Commented Dec 28, 2013 at 11:13
  • Then What is Your Question? Commented Dec 28, 2013 at 11:13
  • Where is the code where you use this class and call its methods? Commented Dec 28, 2013 at 11:14
  • @peeskillet I think OP is asking for that class which is not here.. Commented Dec 28, 2013 at 11:16
  • Also it would help to actually have an array in the class, since that is the requirement. Also make use of that array in your read method Commented Dec 28, 2013 at 11:16

4 Answers 4

2

The problem is that you don't know how many words there are coming. To solve that, you could use an ArrayList.

List<String> entries = new ArrayList<String>();
while (scanner.hasNext())
{
    entries.add(scanner.nextLine());
}
System.out.println(entries);

Access them using the get(int index) method:

String test = entries.get(0); // This will be "car"
Sign up to request clarification or add additional context in comments.

1 Comment

And if you wish to convert it back to an array you can use entries.toArray();
2

if you're willing to use Apache Commons IO then you can do this really easy:

import org.apache.commons.io.FileUtils;

String[] linesArr = new String[0];
List<String> lines = FileUtils.readLines(new File("FILE_NAME.txt"));
if (lines != null) {
     linesArr = lines.toArray(linesArr);
}

2 Comments

Im a strong supporter of using libraries, although I am not sure if its good for total beginners. I would think that its better to first understand how you can do something, and from that point on use a library that will probably do it better than you.
@Giannis I agree, but I thought it should be here because it makes life much simpler after you learn the basics. If someone really wants to know the basics I would suggest writing it without even the java.util.Scanner class, i.e. read using FileInputStream, read the bytes and divide to lines, that would be the best learning exercise.
1

Just do:

List<String> lines = new ArrayList<String>();

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
       lines.add(line); // Add line to list
    }
} // Try-with-resources closes reader

You don't need the scanner or anything else fancy when you just looking for whole lines.

If you really need an array not a list at the end you can just read out the array from the final List.

Comments

0

Make a method that reads all data from file and stores in a List as follows.

public ArrayList<String> fileRead(String fileName){
        File           f;
        String         s;
        FileReader     fr = null;
        BufferedReader br = null;
        ArrayList<String>   sl = new ArrayList<String>();
        try {
            f  = new File(fileName); 
            fr = new FileReader(f);
            br = new BufferedReader(fr);
            while((s=br.readLine())!=null){
                sl.add(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
                try {
                    if(br!=null)
                        br.close();
                    if(fr!=null)
                        fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return sl;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.