In fact, I have a method that reads words from a file and writes it into an array. Sample text file:

www mail login password
www1 mail1 login1 password1

but I want to understand which words on the new line and which not, tell me how to do it, now my code looks like this.

BufferedReader fileReader; String buf[] = new String[0]; { try { String str = null; fileReader = new BufferedReader(new FileReader("C:\\...\\src\\model\\file.txt")); while ((str = fileReader.readLine()) != null) { //ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ Π½ΠΎΠ²Ρ‹Π΅ слова String[] newWords = str.split(" "); //создаСм Ρ€Π°ΡΡˆΠΈΡ€Π΅Π½Π½Ρ‹ΠΉ массив String[] result = new String[buf.length + newWords.length]; //ΠΊΠΎΠΏΠΈΡ€ΡƒΠ΅ΠΌ элСмСнты Π² массив System.arraycopy(buf, 0, result, 0, buf.length); System.arraycopy(newWords, 0, result, buf.length, newWords.length); //присваиваСм Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚ΠΈΡ€ΡƒΡŽΡ‰ΠΈΠΉ массив Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΌΡƒ buf = result; } fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } 

    1 answer 1

    I would use plain file and Scanner if you just need to read lines from a text file and output them to the console. Like that:

      package com.company; import java.util.Scanner; import java.io.*; public class Main { public static void main(String[] args) throws FileNotFoundException { // НиТС ΠΏΡƒΡ‚ΡŒ ΠΊ Ρ„Π°ΠΉΠ»Ρƒ File myFile = new File("C:\\Users\\User\\Projects\\Schitka\\src\\com\\company\\Test.txt"); // БвязываСм ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ Scanner с нашим Ρ„Π°ΠΉΠ»ΠΎΠΌ Scanner scanf = new Scanner(myFile); String temp =""; // Пока Π² Ρ„Π°ΠΉΠ»Π΅ Π΅ΡΡ‚ΡŒ строки while (scanf.hasNextLine()){ System.out.println(scanf.nextLine()); // ΠΈΠ»ΠΈ temp=scanf.nextLine(); // temp ΠΌΠΎΠΆΠ½ΠΎ Ρ€Π°Π·Π±ΠΈΡ‚ΡŒ ΠΏΠΎ раздСлитСлям ΠΈ Π·Π°ΠΏΠΎΠ»Π½ΠΈΡ‚ΡŒ словами массив ΠΈΠ»ΠΈ сразу ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒ temp для Ρ‡Π΅Π³ΠΎ-Π»ΠΈΠ±ΠΎ. } scanf.close(); } } 

    If you need to read Russian words from a file, open the file in binary mode, and after working with it, close it using the method

      .close(); 

    If you need to read each character in the string

      FileReader fileOut = null; try { fileIn = new FileReader("Test.txt"); int a; while((a = fileIn.read()) != -1) { fileOut.write(a); } } finally { if (fileIn != null) { fileIn.close(); }