How to Add Python’s File Handler to Java


Java Assignment HelpFollowing on from the last post where we added a range operation to Java, we will add a simple iterator that allows you to read a file line by line the same way you would do in Python.


import java.util.Iterator;

public class ReadFile implements Iterable<String>, Iterator<String> {

private File file;

private BufferedReader bufferedReader;

private String line;

public ReadFile(String filename) {

this(new File(filename));


public ReadFile(File file) {

this.file = file;

try {

bufferedReader = null;

bufferedReader = new BufferedReader(new FileReader(file));

} catch (FileNotFoundException e) {




public Iterator<String> iterator() {

return this;



public boolean hasNext() {

if (bufferedReader != null) {

try {

line = bufferedReader.readLine();

if (line == null) bufferedReader.close();

} catch (IOException e) {

line = null;



return line != null;



public String next() {

return line;



public static void main(String[] args) {
for (String line : new ReadFile(“test.txt”)) {

You can either pass a file name or a file handle, if you pass a file name then the file is opened. To make it so that we can use it in a loop, it needs to implement an iterator and also be iterable. The file is automatically closed after the iterator is completed, and no exceptions are thrown so you don’t need to add exception handlers to your code.

You could extend this to allow you to read a csv file, and to automatically split the line on commas, deal with quoted string fields etc. If there are other language features you’d like to see implemented contact us, and make a suggestion, or if you are willing to pay then we can write code specifically for you to implement the code you desire.

We have provided Java assignment help to thousands of students solutions in Java and many more in other programming languages. It is always better to send in your requests with plenty of time, as that gives you time to review the solution we provide and also that it allows us time to find an expert to fulfill your request (we can get busy especially near the end of term when multiple large projects may due at the same time). It is also worth sending course notes if they are available as we can ensure the solution provided matches the style and knowledge levels that are expected.

At if you want someone to provide Java homework help, just visit our site and submit an assignment for a quote.


Please enter your comment!
Please enter your name here