Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save oleglomako/51b47de31a336335ccd4d138fcb379e0 to your computer and use it in GitHub Desktop.
Save oleglomako/51b47de31a336335ccd4d138fcb379e0 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileLineByLine {
// построчное считывание файла
public static void main(String[] args) {
try {
File file = new File("/Users/prologistic/file.txt");
//создаем объект FileReader для объекта File
FileReader fr = new FileReader(file);
//создаем BufferedReader с существующего FileReader для построчного считывания
BufferedReader reader = new BufferedReader(fr);
// считаем сначала первую строку
String line = reader.readLine();
while (line != null) {
System.out.println(line);
// считываем остальные строки в цикле
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Kuprich
Copy link

Kuprich commented Jan 9, 2020

Спасибо, я только изучаю Java. Мне очень помогло

@toberlino
Copy link

toberlino commented Sep 4, 2020

почему ресурс не закрыли?

@toberlino
Copy link

toberlino commented Sep 4, 2020

В конце можно добавить
finally{ try { if (reader != null) reader.close(); } catch (IOException e) { e.printStackTrace(); } }
Или использовать try с ресурсами

@aelys-er
Copy link

th u so much, it's very helpfull

@ElenaPre
Copy link

Благодарю! А можно ли читать файл с произвольно места, а не с начала

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment