K
K
krembrule20162017-01-09 19:27:57
Java
krembrule2016, 2017-01-09 19:27:57

How to correctly read and convert the contents of a text file?

Good time of the day!
Faced the problem of converting the contents of a text file. There is no need to make any changes directly to the file itself.

Print result = () -> {    
        try(FileReader text = new FileReader("C:\\text.txt")) {
            
            while(( c = text.read()) != -1)
            {
                y += 1;
                
            }
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            return 0;
        }
        return y;
    };

Thus, I read the file and print its contents to the console. (Krakozyabras are displayed, but this is not about that now) Ideally, I need the content to also be written to the character array, but that's the problem. To create an array char[], you need to know its size, I would like to create a variable with the required size. That is why I ycount the number of characters in the file in a variable.
Then I create an array of the size I need. To fill it with characters from a text file, I think it is necessary to reuse the counting chunk approach, but this is where the problems arise:
char[] a = new char[(int)result.Printer()-1];
while(( c = text.read()) != -1)
            {
                y += 1;
                char[] a = c; Вот тут возникает ошибка
                char[] a = (char)c; Так тоже не выходит
                а как надо?
            }

Am I moving in the right direction at all? Can immediately make an array of obviously larger size? However, even with this approach, I run into the same type problem...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Alexandrov, 2017-01-09
@krembrule2016

public static void main(String[] args) {
        System.err.print(Arrays.toString(test()));
    }
    private static char[] test(){  
        StringBuilder sb = new StringBuilder();
        try( BufferedReader br = new BufferedReader(new FileReader("D:\\text.txt"))) {
            String str;
            while( (str = br.readLine()) != null){
                sb.append(str);
            }
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
           return sb.toString().toCharArray();
        }
       return sb.toString().toCharArray();
    }
}

Output:
run:
[a, s, d, a, s, f, g, a, s, f, d, a, s, d, s, d, g, s, d, g, a, d, f , h, b, s, a, b, w, 4, q, g, , g, 3, , t, , 3, g, , 3, g, 3, g, , , g, r, v, 3 ]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question