Adam Sh
Adam Sh

Reputation: 8577

Java/ read from .txt file

I have .txt file, and I want to read from it to char array.

I have problem, in the .txt file I have:

1  a

3  b

2  c

which mean that a[1]='a', a[3]='b', a[2]='c'.

How in reading the file, I ignore from spaces, and consider the new lines? Thanks

Upvotes: 1

Views: 730

Answers (2)

Eric W.
Eric W.

Reputation: 814

It's probably easiest to use a Scanner.

ArrayList<String> a = new ArrayList<String>();
Scanner s = new Scanner(yourFile);
while(s.hasNextInt()) {
    int i = s.nextInt();
    String n = s.next();
    a.add(n);
}

Of course, this boldly assumes correct input; you should be more paranoid. If you need to deal with each line specially, you can use hasNextLine() and nextLine(), and then split the line using split() from the String class.

Upvotes: 0

dacwe
dacwe

Reputation: 43504

I would suggest you to use a Map for this instead since it's better suited for this kind of problems.:

public static void main(String[] args) {

    Scanner s = new Scanner("1 a 3 b 2 c"); // or new File(...)

    TreeMap<Integer, Character> map = new TreeMap<Integer, Character>();

    while (s.hasNextInt())
        map.put(s.nextInt(), s.next().charAt(0));
}

If you would like to convert the TreeMap to char[] you can do the following:

char[] a = new char[map.lastKey() + 1];

for (Entry<Integer, Character> entry : map.entrySet())
    a[entry.getKey()] = entry.getValue();

Notes:

  • This solution does not work with negative indexes
  • Takes only the "first" character if more than one

Upvotes: 1

Related Questions