Last active
October 24, 2023 04:28
-
-
Save oleglomako/51b47de31a336335ccd4d138fcb379e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
почему ресурс не закрыли?
В конце можно добавить
finally{ try { if (reader != null) reader.close(); } catch (IOException e) { e.printStackTrace(); } }
Или использовать try с ресурсами
th u so much, it's very helpfull
Благодарю! А можно ли читать файл с произвольно места, а не с начала
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Спасибо, я только изучаю Java. Мне очень помогло