简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM