Jdk8 stream api iterate file list

hi guys,
please see below sample code, i have throws IO Exception, but at line :
Files.lines(Paths.get(f.getAbsolutePath()), StandardCharsets.UTF_8),
IDE(eclipse luna) still show there's unhandled exception, did anyone know why ?
public void search2() throws IOException {
  File dir = new File(userLogPath);
  File[] files = dir.listFiles();
  List<File> fileList = new ArrayList<>();
  Arrays.stream(files)
  .map(f -> Files.lines(Paths.get(f.getAbsolutePath()),
  StandardCharsets.UTF_8))
  .forEach(
  line -> line.filter(l -> l.contains(searchTarget))
  .forEach(s -> System.out.println(s)));

hi guys,
please see below sample code, i have throws IO Exception, but at line :
Files.lines(Paths.get(f.getAbsolutePath()), StandardCharsets.UTF_8),
IDE(eclipse luna) still show there's unhandled exception, did anyone know why ?
public void search2() throws IOException {
  File dir = new File(userLogPath);
  File[] files = dir.listFiles();
  List<File> fileList = new ArrayList<>();
  Arrays.stream(files)
  .map(f -> Files.lines(Paths.get(f.getAbsolutePath()),
  StandardCharsets.UTF_8))
  .forEach(
  line -> line.filter(l -> l.contains(searchTarget))
  .forEach(s -> System.out.println(s)));

Similar Messages

  • How to delete latest opened file in the recent opened files list?

    Does any one know if there is any api to modify the recent opened files list under the meun File->Open Recent File?

    There is not.

  • Java does not get file list from shared folder in another server.

    Hi,
    I'm using java 1.4.2.16,
    Command below does not get file list.
    import java.io.;*..
    File file = new File("\\\\10.242.22.28\\SapMII");
    File[] files = file.listFiles();
    SapMII folder is Everyone full Control permission.
    How can i solve this problem?
    Thanks.

    Could you please post replies in a more helpful way? Just informing me that it was an NPE doesn't really tell me anything. Post the stacktrace (Exception#printStackTrace()). And the listFile() methods API has this to say:
    Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.I'm able to run this sample code easily:
    import java.io.File;
    public class TestFileList {
         public static void main(String[] args) {
              File file = new File("\\\\10.40.55.33\\shared");
              File [] files = file.listFiles();
              for(File currentFile: files )
                   System.out.println(currentFile.getName());
    }

  • Using File.list()

    Hi,
    Im using FMS 3 on the server side when onConnect occures i
    need an array of all file that is the directory root/streams/myApp
    how do use the File.list() ? do i need to create a new file
    just for getting the list of files of the directory? and how do i
    get to do that on the directory i want ? is it like this:
    File.list(function(name){ return
    name.indexOf("streams/myApp/")!=-1);
    i so the example in the doc files :
    var a = x.currentDir.list(function(name){return
    name.length==3;});
    does x is a File object? and where the currentDir came from
    its not a File property?
    Please help ...

    In SSAS, File objects represent both files and directories.
    The "x" in the examples just means "arbitrary thing that has
    a member of whatever type we're talking about." In this case, "x"
    is something that has a member called "currentDir" that's a File
    object (presumably representing the current directory).
    I'm pretty sure you can create an equivalent like this:
    currentDir = File(".");
    Also, your search isn't going to work the way you expected.
    The find function doesn't search all subfolders recursively, and
    the name parameter only gets the filename (the last component of
    the path), not the entire pathname. You're going to want to open
    streams/myApp as a File, then just list everything in it.

  • Need to know how to iterate a list of field from the req xml in page servic

    Hi All,
    Please help me out with java code in which i am able to iterate a list of field coming in the request xml to my page service class under read(Pageheader header) method of mine queryPagemaintenace class.
    package com.splwg.cm.domain.pageService;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    import com.ibm.icu.math.BigDecimal;
    import com.splwg.base.api.businessObject.BusinessObjectDispatcher;
    import com.splwg.base.api.businessObject.BusinessObjectInstance;
    import com.splwg.base.api.businessObject.COTSInstanceListNode;
    import com.splwg.base.api.datatypes.Date;
    import com.splwg.base.api.lookup.BusinessObjectActionLookup;
    import com.splwg.base.api.service.DataElement;
    import com.splwg.base.api.service.ItemList;
    import com.splwg.base.api.service.PageHeader;
    import com.splwg.shared.common.ApplicationError;
    import com.splwg.shared.environ.FieldDefinition;
    import com.splwg.shared.environ.ListDefinition;
    import com.splwg.shared.logging.Logger;
    import com.splwg.shared.logging.LoggerFactory;
    * @author
    @QueryPage (program = CMUSER, service = CMUSER,
    * body = @DataElement (contents = { @ListField (name = USER_GROUP_LIST)
    * , @ListDataField (name = USR_GRP_ID)
    * , @DataField (name = MESSAGE_TEXT)
    * , @DataField (name = USER_ID)
    * , @DataField (name = PASSWORD)
    * , @DataField (name = LAST_NAME)
    * , @DataField (name = FIRST_NAME)
    * , @DataField (name = USER_TYPE_FLG)
    * , @DataField (name = EMAILID)}),
    * actions = { "add"
    * ,"read"
    * , "delete"
    * , "change"},
    * header = { @DataField (name = USER_TYPE_FLG)
    * , @DataField (name = EMAILID)
    * , @DataField (name = LAST_NAME)
    * , @DataField (name = FIRST_NAME)
    * , @DataField (name = PASSWORD)
    * , @DataField (name = USER_ID)},
    * headerFields = { @DataField (name = USER_TYPE_FLG)
    * , @DataField (name = USR_GRP_ID)
    * , @DataField (name = EMAILID)
    * , @DataField (name = LAST_NAME)
    * , @DataField (name = FIRST_NAME)
    * , @DataField (name = PASSWORD)
    * , @DataField (name = USER_ID)},
    * lists = { @List (name = USER_GROUP_LIST, size = 100, includeLCopybook = false,
    * body = @DataElement (contents = { @DataField (name = USR_GRP_ID)}))},modules = {})
    public class CMUSER extends CMUSER_Gen {
    public static final Logger logger = LoggerFactory.getLogger(CMUSER.class);
         DataElement root = new DataElement();
         PageHeader page = new PageHeader();
         protected DataElement read(PageHeader header) throws ApplicationError{
    I want to know how can i iterate this USER_GROUP_LIST in my read method and get the USR_GRP_ID field data from it.
    A Prompt reply from your end will help me to resolve this issue

    Guru Sir,
    i tried to override the add() method of the framework in that i was able to iterate the field from the list. But now the i am facing there is that i am not able to send back the response to the external system in XML format. I am getting a blank response in my SOAP UI Tool while testing here is the code:
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    import com.ibm.icu.math.BigDecimal;
    import com.splwg.base.api.businessObject.BusinessObjectDispatcher;
    import com.splwg.base.api.businessObject.BusinessObjectInstance;
    import com.splwg.base.api.businessObject.COTSInstanceListNode;
    import com.splwg.base.api.datatypes.Date;
    import com.splwg.base.api.lookup.BusinessObjectActionLookup;
    import com.splwg.base.api.service.DataElement;
    import com.splwg.base.api.service.ItemList;
    import com.splwg.base.api.service.PageHeader;
    import com.splwg.shared.common.ApplicationError;
    import com.splwg.shared.logging.Logger;
    import com.splwg.shared.logging.LoggerFactory;
    * @author
    @QueryPage (program = CMUSER4, service = CMUSER4,
    * body = @DataElement (contents = { @DataField (name = MESSAGE_TEXT)
    * , @DataField (name = PASSWORD)
    * , @DataField (name = USER_ID)
    * , @DataField (name = LAST_NAME)
    * , @DataField (name = FIRST_NAME)
    * , @DataField (name = USER_TYPE_FLG)
    * , @DataField (name = EMAILID)
    * , @ListDataField (name = USR_GRP_ID)
    * , @ListField (name = USER_GROUP_LIST)}),
    * actions = { "add"
    * , "delete"
    * , "change"
    * , "read"},
    * header = { @DataField (name = USER_ID)
    * , @DataField (name = MESSAGE_TEXT)},
    * headerFields = { @DataField (name = USER_ID)
    * , @DataField (name = MESSAGE_TEXT)},
    * lists = { @List (name = USER_GROUP_LIST, size = 100,
    * body = @DataElement (contents = { @DataField (name = USR_GRP_ID)}))}, modules = {})
    public class CMUSER4 extends CMUSER4_Gen {
         public static final Logger logger = LoggerFactory.getLogger(CMUSER4.class);
         DataElement root = new DataElement();
         PageHeader page = new PageHeader();
         protected PageHeader add(DataElement item) throws ApplicationError{
              BusinessObjectInstance boInstance = BusinessObjectInstance.create("CM-USER");
              String USR_GRP_ID = null;
              try{
              logger.info("Data coming from the Service into the Application is :"+item.get(STRUCTURE.USER_ID));
              logger.info("Data coming from the Service into the Application is :"+item.get(STRUCTURE.FIRST_NAME));
              logger.info("Data coming from the Service into the Application is :"+item.get(STRUCTURE.LAST_NAME));
              logger.info("Data coming from the Service into the Application is :"+item.get(STRUCTURE.EMAILID));
              // logger.info("Data coming from the Service into the Application is :"+getInputHeader().getString(STRUCTURE.list_USER_GROUP_LIST.USR_GRP_ID));
              // Iterator it = STRUCTURE.
              ItemList sourceList = item.getList(STRUCTURE.list_USER_GROUP_LIST.name);
              List userGrpID = new ArrayList();
              logger.info("The Size of the User Group List here is :"+sourceList.size());
              Iterator iter;
              if ((sourceList != null) &&
              (sourceList.size() > 0)) {
              for (iter = sourceList.iterator(); iter.hasNext(); ) {
              DataElement myItem = (DataElement)iter.next();
              USR_GRP_ID = myItem.get(STRUCTURE.list_USER_GROUP_LIST.USR_GRP_ID);
              logger.info("The User Group Id coming in the List here is :"+USR_GRP_ID);
              logger.info("Data coming from the Service into the Application is :"+item.get(STRUCTURE.PASSWORD));
              boInstance.set("user", item.get(STRUCTURE.USER_ID));
              boInstance.set("firstName", item.get(STRUCTURE.FIRST_NAME));
              boInstance.set("lastName", item.get(STRUCTURE.LAST_NAME));
              boInstance.set("emailAddress", item.get(STRUCTURE.EMAILID));
              // COTSInstanceList userGrpList = boInstance.getList("userGroupUser");
              // COTSInstanceListNode userGroupList = userGrpList.newChild();
              COTSInstanceListNode userGroupList = boInstance.getList("userGroupUser").newChild();
              userGroupList.set("userGroup", USR_GRP_ID);
              logger.info("Data coming from the Service into the Application is :"+userGroupList.toString());
              /*boInstance.set
              boInstance.set("userGroup", getInputHeader().getString(STRUCTURE.HEADER.USR_GRP_ID));*/
              // UserTypeLookup.constants.TEMPLATE_USER
              //if(element.get(STRUCTURE.USER_TYPE_FLG))
              //boInstance.set("user", element.get(STRUCTURE.));
              boInstance.set("dashboardWidth","200");
              boInstance.set("homeNavigationOption","CI0000000574");
              boInstance.set("language","ENG");
              boInstance.set("toDoEntriesAge1", new BigDecimal(50));
              boInstance.set("toDoEntriesAge2",new BigDecimal(100));
              boInstance.set("displayProfileCode", "NORTHAM");
              String expirationDate = "2100-12-31";
              String[] array = expirationDate.split("-");
              userGroupList.set("expirationDate",new Date(Integer
                             .parseInt(array[0]), Integer
                             .parseInt(array[1]), Integer
                             .parseInt(array[2])));
              //boInstance.set("userGroupUser", userGroupList);
              COTSInstanceListNode roleUserList = boInstance.getList("roleUser").newChild();
              roleUserList.set("toDoRole","F1_DFLT");
              COTSInstanceListNode dataAccessList = boInstance.getList("dataAccessUser").newChild();
              dataAccessList.set("dataAccessRole","***");
              String expiryDate = "2100-01-01";
              String[] array1 = expiryDate.split("-");
              dataAccessList.set("expireDate",new Date(Integer
                             .parseInt(array1[0]), Integer
                             .parseInt(array1[1]), Integer
                             .parseInt(array1[2])));
              BusinessObjectDispatcher.execute(boInstance,
                             BusinessObjectActionLookup.constants.FAST_ADD);
              page.put(STRUCTURE.HEADER.MESSAGE_TEXT, "User Added Successfully");
              page.put(STRUCTURE.HEADER.USER_ID,item.get(STRUCTURE.USER_ID));
              }catch(Exception e){
                   e.printStackTrace();
                   page.put(STRUCTURE.HEADER.MESSAGE_TEXT, "Caught Exception in the ORMB System. Please reach out to the Admin"+e.getMessage());
                   page.put(STRUCTURE.HEADER.USER_ID,item.get(STRUCTURE.USER_ID));
              return page;
    If you can help me to find out what went wrong here while sending the response back it can close my issue.

  • Get the file list of a given directory

    does anyone know how to get the file list of a given directory? I tried "list"/"filelist" but the class not found.
    THanks!

    What made you assume that there exist classes called list or filelist etc.
    Do you read API documentation etc ?
    Anyways, here is a hint java.io.File.listFiles()

  • New Stream API and I/O streams - Any overlap?

    I know the new Stream API is for processing object streams, often from collections.
    But is this notion applicable to I/O streams, too?
    It definitely seems compelling to use a functional approach to I/O streams that supports parallelism.
    Let me know if my question doesn't make any sense to you
    Thanks
    Oliver

    Indeed, there is some interplay between the APIs.
    For example BufferedReader defines a lines() method that returns a (lazily-read) Stream<String>, each element being a line. The Files class in java.nio.file has a utility lines(Path path) method.
    So assuming you have some class MyClass, some MyClassParser with a parse method, you can use idioms like
    void processFile(Path path) throws IOException {
        MyClassParser parser = ... ;
        try (Stream<String> lines = Files.lines(path)) {
            lines.map(parser::parse).forEach( myObject -> ...);
    If you want to parallelize it, do
    lines.parallel().map(parser::parse)...
    (assuming your parser.parse method can handle multiple threads)

  • Api Function to list port in use

    Hi!I'm looking for an Api Function to list a ports in use in a Essbase Serve.

    Although there is currently no Api function to check the ports in use, if you are using Essbase 6.5 there are a couple other methods that could be used. (Might work in 6.2 but I didn't check).Check out the following functions in Maxl:- display system- display session all "Display system" displays how many ports are available - if you know how many you have then you know how many are in use. "Display session all" displays the users and their tcpip address - allowing you to determine the number of ports in by counting the number of unique user id + tcpip addresses. A worse case scenario to capture this information would be a program that runs the Maxl script to output a file that is then parsed.Hope this helps,- Jay---------------------------Jay NishSenior Business Intelligence ConsultantClarity SystemsEmail: [email protected]: www.claritysystems.com

  • Using the array of file names from File.list()

    Hi
    I'm having trouble with my code, similar to this:
    File temp=new File(path); //where 'path' is a String containing the directory path
    String [ ] arr = temp.list();
    Then when trying to use arr, I come up with NullPointerExceptions.
    The Java API says that the File.list() method returns a Stirng array.
    But then how do I use/get this array in a nice usable form?
    (eg. to be able to loop through the list of {returned} Files)

    Yes I have referred closely to the documentation.
    The method list() for my File object is definitely not returning null;
    it seems that as soon as the code inside the loop tries to access the next element of the returned array [the one after the last existing element] - which is actually non-existent (ie overstepped the bounds of the array's index) - the program comes up with an Exception*. So the method list() does not return null...
    I have managed a workaround similar to this:
            File temp = new File (path);
            String[] list = new String [temp.list ().length + 1];
            try
                for (int i = 0 ; temp.list () != null ; i++)
    list [i] = temp.list () [i];
    catch (ArrayIndexOutOfBoundsException iobe)
    * The program is not coming up with NullPointerExceptions anymore; only an ArrayIndexOutOfBoundsException if I comment out the try and catch coding.... (?)
    Thanks for your suggestion about posting this at the Java Programming Forum.
    My workaround works, but is there a way to do this without catching an exception?

  • How does one change the font size for folders and/or file lists in the Bookmarks Library?

    How does one change the font size for folders and/or file lists in the '''Bookmarks''' Library?
    Since the upgrade to version 9.0.1 of Firefox, the Bookmarks feature changes are confusing me. They seem to be confusing themselves as well. The list of bookmarks has changed. The font size is so small that my aging eyes cannot read it without fogging the screen with my breath. Some folders are out of alphabetical order (where I know they were previously good), and some are missing altogether (folders to which I frequently add references).
    As for missing or deranged files or folders, was there something that I should have done or now need to do to recover those after the upgrade (or before)?
    With regard to font size,
    1. there is no “Edit Bookmarks” or like option to edit the list in this version
    2. the “zoom” option in the “view” list of functions is greyed out when in “Show All Bookmarks” window
    3. expanding the browser window has no effect on font size
    4. “Preferences” settings for font size has no effect in that window either, including advanced settings
    5. “Help” offers none that I can find.
    Can any of you Help?!?

    Maybe this extension helps:
    *Theme Font & Size Changer: https://addons.mozilla.org/firefox/addon/theme-font-size-changer/

  • URLs in orphaned file list?

    when I check for orphaned files on my very old, very messy
    website I see urls like "/http:/java.sun.com",
    "mailto:[email protected]" and nothing happens when I choose
    "open file". I can delete them from the list but when I run the
    orphaned files check again they're all back! what's going on?
    I recognize most of these as files and links that were
    deleted long ago (them and the pages that linked to them). How is
    dreamweaver finding these links and what are they doing in the
    orphaned files list?

    > I recognize most of these as files and links that were
    deleted long ago
    Under the main dw menu->Site->Advanced->Rebuild Site
    Cache.
    Alan
    Adobe Community Expert, dreamweaver
    http://www.adobe.com/communities/experts/

  • Computer Contents in File List

    My file list now contains all of the items and files in my
    computer, including all materials on my back-up hard drive and the
    network. How do I delete this from the file list.

    That's normal- it belongs there. ignore it or use when it's
    handy.
    It's use is to find and copy files that are outside of the
    Local site folder
    while staying inside of dreamweaver.
    If it wasn't there- you'd have to go to the Desktop or My
    Computer, browse
    to the file, copy it, browse to the Local Site Folder, paste,
    then go back
    into dreamweaver.
    suggestion- go to the Help menu-->Using
    Dreamweaver-->the dreamweaver
    workspace or similar wording.
    > I am new to Dreamweaver 8 but there is s drop down menu
    under file. The drop
    > down is titled computer and when the drop down is open
    my options are
    > Macintosh
    > HD, PSP5000 (which is my back-up drive) and network.
    Separated by a line is
    > manage sites. Does this help?
    >

  • Unable to clear the recently open files list

    Currently, in order to clear the opened files list, the user has to go into the Windows registry.  This by itself can be bad if the user is not familiar with the registry; could mess up the registry if not very careful.  There appears to be no plug-in/addon for this option nor is there any user option to select to clear the list.  There is a setting in the options/permissions to limit the number of opened files to the list; the minimum number being one(1).  Cannot set this number to zero(0) unless maybe there is a registry fix for this.  I want to suggest that in the next release, or at least as soon as possible, to add to the Adobe Reader (by default) a user option to be able to clear this list with having to enter the registry.  Or, maybe create a plugin/addon to perform this action.  That's it.

    Hi Ineedtoknownow
    You can raise your feature request on below link : https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform

  • How to use dynamic file as welcome-file-list in web.xml

    I have configured my web.xml file as this,
    <web-app>
    <context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.xhtml</param-value>
    </context-param>
    <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
    <welcome-file>login.jsf</welcome-file>
    </welcome-file-list>
    </web-app>
    and my login.xhtml file as this,
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:c="http://java.sun.com/jstl/core"
    xmlns:f="http://java.sun.com/jsf/core">
    <body>
    <f:view>
    <h:form>
    UserName:<h:inputText id="userName"
    value="#{bean.userName}" rendered="true"
    required="true"/>
    Password:<h:inputText id="password"
    value="#{bean.password}" rendered="true"
    required="true"/>
    <h:commandButton id="submit" value="Submit" action="#{bean.authenticate}" />
    </h:form>
    </f:view>
    </body>
    </html>
    but when i deploy this using tomcat and try to put url as this,
    http://localhost:8080/project
    Its not identifying welcome file from web.xml
    I am getting error like this,
    The requested resource (/project/) is not available.
    How to resolve this,
    Thanks,
    Vinutha

    This might help:
    http://forum.java.sun.com/thread.jspa?threadID=696586
    As well, you might have to change the servlet-mapping in your web.xml. The url-pattern, I think, needs to be .xhtml. Your login.jsf file in the welcome list will need to be renamed to login.xhtml.
    CowKing

  • After successful install, I am unable to use RoboHelp 7 because of constant refresh of file lists

    RoboHELP 7 installed on Windows XP
    Our enterprise support team installed RH7 on my new laptop via our corporate intranet.  I received an e-mail message reporting that the install failed so I contacted the support team, someone logged on to my machine by remote and did an uninstall of RH7.  Then, the install was done again and the same failure message was received.  Then, RH was uninstalled and the install was attempted for the third time.  Again, I received the failure message.  I had noticed that after each install the icons appeared on my desktop.  So, after this third install, I went ahead and clicked the RH7 HTML icon and the program seemed to start properly.  I have a key number from our enterprise team and I entered the key number to complete the registration.  The UI appeared and I selected my recent project.  RH built the file lists that I expected to see in the left panes of the interface but the file lists kept "twitching" and the cursor kept changing to the hourglass and back.  This happened about once every two or three seconds and I could not move my cursor fast enough to select a file.
    One of my co-workers suggested that I uninstall RH7 myself, check the registry and erase any robohelp entries.  I know this is risky but I am confident I can do it.  However, I would like to hear from any RH experts about how to solve this "twitching" problem, if there are other possible solutions.  Thanks.

    My gut feel is that if your organisation is large enough to have an Enterprise license, IT would not take too kindly to you uninstalling the product yourself and editing the registry. That's your issue though.
    If they are happy, then you could try www.revouninstaller.com with which a number of people have reported good results if you use the stronger options to clear the registry. Again at your risk and responsibility.
    You might also like to look at http://www.adobe.com/devnet/robohelp/articles/before_install.html. It includes the script IT should be using. Maybe that should be checked as well.
    The other approach is to get them to do a direct install. Worth trying given the issues you are having.
    See www.grainge.org for RoboHelp and Authoring tips

Maybe you are looking for