Reading from files character-by-character into a JAVA array


You need to read from the file character-by-character into the array and in the future so that you can process the elements of the array( search for So_to_The element and its removal from the array, but this is not the main thing)

Author: Владимир92, 2012-11-06

2 answers

Something like this:

BufferedReader bufferedReader = new BufferedReader(new FileReader(".//src//file//file.txt"));

int symbol = bufferedReader.read();
while (symbol != -1) {  // Когда дойдём до конца файла, получим '-1'
      // Что-то делаем с прочитанным символом
      // Преобразовать в char:
      // char c = (char) symbol;
      symbol = bufferedReader.read(); // Читаем символ
}
 2
Author: pkamozin, 2012-11-06 16:07:59

Character-by-character reading from a text file to an ArrayList (useful if you don't know the number of characters; you can replace it with a LinkedList, depending on what operations you need later)

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    private static List<Character> chars = new ArrayList<>();

    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(new File("myfile.txt")));

            int c;
            while ((c = reader.read()) != -1) {
                chars.add((char) c);
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println(chars.toString());
    }

}
 1
Author: phvoronov, 2012-11-06 16:14:04