Java Path File Read nio readFile(String path)

Here you can find the source of readFile(String path)

Description

read File

License

Apache License

Declaration

public static List<String> readFile(String path) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static List<String> readFile(String path) {
        List<String> contexts = new ArrayList<>();
        try {/*from w w w. jav  a  2  s . c o  m*/
            Stream<String> content = Files.lines(Paths.get(path));
            Stream<String> tuples = content.flatMap(line -> {

                //Separating label and values
                return Arrays.stream(line.split(";")).map(t -> {

                    String[] values = t.split(",");
                    String label = values[0];
                    String[] predicates = values[1].split("_");

                    predicates[0] = "battery:" + Double.valueOf(predicates[0]);
                    predicates[1] = "bright:" + Double.valueOf(predicates[1]);
                    predicates[2] = "screen:" + Double.valueOf(predicates[2]);
                    predicates[3] = "power:" + Double.valueOf(predicates[3]);
                    predicates[4] = "headset:" + Double.valueOf(predicates[4]);
                    predicates[5] = "app:" + Double.valueOf(predicates[5]);
                    predicates[6] = "period:" + Double.valueOf(predicates[6]);
                    predicates[7] = "time:" + Double.valueOf(predicates[7]);
                    predicates[8] = "gps:" + Double.valueOf(predicates[8]);

                    //                    return label + "\t" + String.join(" ", predicates);
                    return String.join(" ", predicates) + "," + label;
                });

            });

            contexts.addAll(tuples.collect(Collectors.toList()));
            content.close();

            PrintWriter writer = new PrintWriter(new File("dataset.csv"), "UTF-8");
            for (String context : contexts) {
                writer.println(context);
            }

            writer.flush();
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Total: " + contexts);
        return contexts;
    }
}

Related

  1. readFile(Path path)
  2. readFile(String path)
  3. readFile(String path)
  4. readFile(String path)
  5. readFile(String path)
  6. readFileAsString(String filePath)
  7. readFileAsString(String path)
  8. readFileByLines(String filePath)
  9. readFileIntoString(Path path)