Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8102433
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T23:14:27+00:00 2026-06-05T23:14:27+00:00

i am still new to the Java language and libraries… i often use this

  • 0

i am still new to the Java language and libraries… i often use this kind of pattern in Python, and wonder how i should implement this one with Java.

i need to read a huge file line by line, with some kind of xml marking (i am producing the input, so i am sure that there will not be any ambiguity)

i want to iterate inside some parts of the huge file like the python code below :

(using the yield / python iterator pattern… is there any equivallent in Java? i really do like the for item in my collection: yield something_about(many items))

what will be the best (java) way to implement this kind of behaviour ?

thx

first EDIT: BTW, i would have also be interested in the similar mapping between List and File that are available from a Python point of view when using file and [python list,] if of course possible with Java => answer : see Jeff Foster suggestion of using : Apache.IOUtils

def myAcc(instream, start, end):
    acc = []
    inside = False
    for line in instream:
        line = line.rstrip()
        if line.startswith(start):
            inside = True
        if inside:
            acc.append(line)
        if line.startswith(end):
            if acc:
                yield acc
                acc = []
            inside = False


f = open("c:/test.acc.txt")

s = """<c>
<a>
this is a test
</a>
<b language="en" />
</c>
<c>
<a>
ceci est un test
</a>
<b language="fr" />
</c>
<c>
<a>
esta es una prueba
</a>
<b language="es" />
</c>"""

f = s.split("\n")   # here mimic for a input file...

print "Reading block from <c> tag!"
for buf in myAcc(f, "<c>", "</c>"):
    print buf # actually process this inner part... printing is for simplification
    print "-" * 10

print "Reading block from <a> tag!"
for buf in myAcc(f, "<a>", "</a>"):
    print buf  # actually process this inner part...
    print "-" * 10    

OUTPUT :

Reading block from <c> tag!
['<c>', '<a>', 'this is a test', '</a>', '<b language="en" />', '</c>']
----------
['<c>', '<a>', 'ceci est un test', '</a>', '<b language="fr" />', '</c>']
----------
['<c>', '<a>', 'esta es una prueba', '</a>', '<b language="es" />', '</c>']
----------
Reading block from <a> tag!
['<a>', 'this is a test', '</a>']
----------
['<a>', 'ceci est un test', '</a>']
----------
['<a>', 'esta es una prueba', '</a>']
----------

so directly inspired by the answer of Jeff Foster below, here is a try to solve my trouble and do the same kind of thing than my python code :

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

interface WorkerThing { 
    public void doSomething(List<String> acc); 
} 

class ThatReadsLargeFiles { 
    public void readAHugeFile( BufferedReader input, String start, String end, WorkerThing action) throws IOException { 
        // TODO write some code to read through the file and store it in line 
        List<String> acc = new ArrayList<String> ();
        String line; 
        Boolean inside = false;
        while ((line = input.readLine()) != null) {
            if (line.equals(start)) {
                inside = true;
            }
            if (inside) {
                acc.add(line);
            }
            if (line.equals(end)) {
                if (acc != null && !acc.isEmpty()) { // well not sure if both are needed here...
                    // Here you are yielding control to something else
                    action.doSomething(acc);
                    //acc.clear(); // not sure how to empty/clear a list... maybe : List<String> acc = new ArrayList<String> (); is enough/faster?
                    acc = new ArrayList<String> (); // looks like this is the *right* way to go!
                }
                inside = false;
                // ending
            }
        } 
        input.close();
    } 
 }

public class YieldLikeTest {

    public static void main(String[] args) throws IOException {


        String path = "c:/test.acc.txt";

        File myFile = new File(path);
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(myFile), "UTF8"));
        //BufferedReader in = new BufferedReader(new FileReader(path, "utf8"));

        new ThatReadsLargeFiles().readAHugeFile(in, "<a>", "</a>", new WorkerThing() {
                public void doSomething(List<String> acc) {
                    System.out.println(acc.toString());
                }
        });


    }

}

second EDIT: i was too fast accepting this answer, actually, i still miss and have a misunderstanding : i do not know how to get and keep trace of the content of accat the @ most upper level (not inside the anonymous class). So that it can be used from the calling for something else than printing say for example instantiate a class, and do other processing… Yield allow this kind of usage, i do not see how i can adapt the proposed answer to have this behaviour. Sorry, my Python usage/sample was to simple.

so here is the answer derived from the Jeff Foster explanation for memorizing the acc:

class betweenWorker implements WorkerThing {

    private List<String> acc;

    public void process(List<String> acc) {
        this.acc = acc;
    }
    public List<String> getAcc() { return this.acc; }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T23:14:28+00:00Added an answer on June 5, 2026 at 11:14 pm

    Java doesn’t support something like the yield, but you can achieve the same sort of thing by creating an interface that encapsulates the action that you’ll perform on the individual lines.

    interface WorkerThing {
      void doSomething(string lineOfText);
    }
    
    class ThatReadsLargeFiles {
        public void readAHugeFile(WorkerThing actions) {
            // TODO write some code to read through the file and store it in line
    
            // Here you are yielding control to something else
            action.doSomething(line);
        }
     }
    

    When you use it you can use anonymous interface implementations to make things slightly more bearable.

    new ThatReadsLargeFiles().readAHugeFile(new WorkerThing() {
        void doSomething(string text) {
            System.out.println(text); 
        }
    };
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm still very new to Java. I'm trying to use CMU's Sphinx4 voice recognition.
I'm still new to programming/Java/Android so I'm trying to understand everything I do and
I'm still relatively new to Java and Android development, so I'm still unfamiliar with
First, i'm new at Java-programming and my native lang is not english, but still
I know that more-dynamic-than-Java languages, like Python and Ruby, often allow you to place
I'm still new to the Java world (former C++ programmer). I designed an Interface
I'm a relatively new java programmer and I've been tinkering around with this program
.NET, Java and other high level database API's in various language often provide techniques
I want to do this (no particular language): print(foo.objects.bookdb.books[12].title); or this: book = foo.objects.bookdb.book.new();
C++ is still an evolving language and new features are being added to it

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.