java - Get content of a file inside a directory -


I want to get the contents of a file into a directory:

  / sys / Block / sda / device / model  

I use this code to get content:

  string content = new string (files .readlbites (Path. ("/ Sys / block / sda / device / model")));  

But in some cases, I have such cases:

  / sys / block / sda / device / model / sys / block / sdb / device    

sd * and how to update all the directories starting with the print I / v> file / Code>?

Can you show me some examples for Java 8 with filters?

This is an example of how to use Java 8 features:

  function & lt; Path, byte []> Uncheck: Read = P -> {Try files back. ReadAllBytes (P); } Grip (IOException pre) {new antiquarian (pre); }}; (Stream & Lt; Path & gt; s = Files.find (Path ("/ Sys / block"), 1, (P, A) - & gt; p.getName (p.getNameCount () - 1) ToString () .marks ("sd")) {s.map (p-> p.resolve ("device / model")). Map (uncheck read) .map (string :: new) .forEach (System.out :: println); }  

This is an example that works for compactness and stand-alone. For real applications, it is possible that you will do it in a slightly different way to use the ICO operation as the Function which does not allow check exceptions, so you have a rapper function Can:

  interface IOFunction & lt; T, R & gt; {R applies (in t) IOException throws; } Fixed & lt; T, R & gt; & Lt; T, R & gt; Rap (IOFunction & lt; T, R & gt; f) {Return to T- & gt; {Try {return f.apply (t); } Grip (IOException pre) {new antiquarian (pre); }}; }  

Then you can use

  (stream  gt; s = Files.find (paths.get (/ " Sys / block "), 1, (P, A) - & gt; P.Jetenam (P.GetEmemcount () - 1) .tasting (). With Startup (" SD "))} {SMAP (P - & gt; P. Resol ("device /model")).map(wrap (files :: readAllBytes) .map (string :: new) .forEach (System.out :: println); }  

But you may use newDirectoryStream even if returned DirectoryStream a stream And therefore a manual stream is required because this method allows such as "sd *" :

  try (DirectoryStream & Lt; path & gt;); Ds = files.newDirectoryStream (paths.get ("/ sys / block"), "sd *")) {stream.support.stream (ds.spliterator (), incorrect) .map (p-> p.resolve ("Device / Model")). Map (wrap (files :: readAllBytes) .map (string :: new) .forEach (System.out :: println); }  

Finally, the option to process files as streams of lines should be specified as:

  Try (DirectoryStream & lt; path & Gt; ds = Files.newDirectoryStream Paths.get ("/ sys / block"), "sd *")) {stream.support.stream (ds.spliterator (), incorrect) .map (p-> p. Resolve ("device / model") Flatmap (rap (files :: line)) .for eca (system out: printline); }  

Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -