14

all,I'm now facing the problem of no idea on storing the content in text file into the array. The situation is like, text file content:

abc1
xyz2
rxy3

I wish to store them into array line by line, is that possible? What I expect is like this:

arr[0] = abc1
arr[1] = xyz2
arr[2] = rxy3

I've try something like this, but seem like not work for me. If anyone can help me, really thanks a lot.

The code is:

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
        String str;

        while((str = in.readLine()) != null){
            String[] arr = str.split(" ");
            for(int i=0 ; i<str.length() ; i++){
                arr[i] = in.readLine();
            }
        }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
salemkhoo
  • 325
  • 1
  • 2
  • 11

12 Answers12

25

I would recommend using an ArrayList, which handles dynamic sizing, whereas an array will require a defined size up front, which you may not know. You can always turn the list back into an array.

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;

List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
    list.add(str);
}

String[] stringArr = list.toArray(new String[0]);
dimid
  • 7,285
  • 1
  • 46
  • 85
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Thanks for your guidance, Kevin, you really help me a lots, thanks! – salemkhoo Apr 19 '13 at 08:25
  • hi Kevin, thanks for your answer, my doubt is how I can print the stringArr when I tried to print the stringArr i am getting some output like [Ljava.lang.String;@17bd8e. Can anyone suggest me what is the correct way to print the contents of stringArr. – Chinmoy Jun 10 '16 at 11:49
  • Use Arrays.toString(stringArr) to print the content of array. – Praveen Kishor Jul 08 '19 at 09:27
13

The simplest solution:

List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]); 

Note that java.nio.file.Files is since 1.7

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
3

This should work because it uses List as you don't know how many lines will be there in the file and also they may change later.

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null){
    lines.add(str);
}
String[] linesArray = lines.toArray(new String[lines.size()]);
dotnetom
  • 24,551
  • 9
  • 51
  • 54
IndoKnight
  • 1,846
  • 1
  • 21
  • 29
  • hi Guys, thanks for the answer, my doubt is how I can print the linesArray when I tried to print the linesArray i am getting some output like [Ljava.lang.String;@d8dc5a. Can anyone suggest me what is the correct way to print the contents of linesArray. – Chinmoy Jun 10 '16 at 10:39
3

JAVA 8 :

Files.lines(new File("/home/abdennour/path/to/file.txt").toPath()).collect(Collectors.toList());
Community
  • 1
  • 1
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
2

You need to do something like this for your case:-

int i = 0;
while((str = in.readLine()) != null){
    arr[i] = str;
    i++;
}

But note that the arr should be declared properly, according to the number of entries in your file.

Suggestion:- Use a List instead(Look at @Kevin Bowersox post for that)

Rahul
  • 44,383
  • 11
  • 84
  • 103
2

Just use Apache Commons IO

List<String> lines = IOUtils.readLines(new FileInputStream("path/of/text"));
Zutty
  • 5,357
  • 26
  • 31
1

Try this:

String[] arr = new String[3];// if size is fixed otherwise use ArrayList.
int i=0;
while((str = in.readLine()) != null)          
    arr[i++] = str;

System.out.println(Arrays.toString(arr));
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
1

When you do str = in.readLine()) != null you read one line into str variable and if it's not null execute the while block. You do not need to read the line one more time in arr[i] = in.readLine();. Also use lists instead of arrays when you do not know the exact size of the input file (number of lines).

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;

List<String> output = new LinkedList<String>();

while((str = in.readLine()) != null){
    output.add(str);
}

String[] arr = output.toArray(new String[output.size()]);
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
1

You can use this full code for your problem. For more details you can check it on appucoder.com

class FileDemoTwo{
    public static void main(String args[])throws Exception{
        FileDemoTwo ob = new FileDemoTwo();
        BufferedReader in = new BufferedReader(new FileReader("read.txt"));
        String str;
        List<String> list = new ArrayList<String>();
        while((str =in.readLine()) != null ){
            list.add(str);
        }
        String[] stringArr = list.toArray(new String[0]);
        System.out.println(" "+Arrays.toString(stringArr)); 
    }

}
sag mag
  • 11
  • 1
0

Suggest use Apache IOUtils.readLines for this. See link below.

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html

yogiam
  • 168
  • 7
0

You can use this code. This works very fast!

public String[] loadFileToArray(String fileName) throws IOException {
    String s = new String(Files.readAllBytes(Paths.get(fileName)));
    return Arrays.stream(s.split("\n")).toArray(String[]::new);
}
0
String a =  "John\n" +
            "Michael Kai\n" +
            "Susan Elrond";
    String[] b = a.split(System.getProperty("line.separator"));
    System.out.println(Arrays.toString(b));
oskan001
  • 11
  • 1