List of usage examples for java.nio.file Files newBufferedReader
public static BufferedReader newBufferedReader(Path path, Charset cs) throws IOException
From source file:Main.java
public static void main(String[] argv) throws Exception { BufferedReader reader = Files.newBufferedReader(Paths.get("a.bat"), StandardCharsets.UTF_8); //BufferedReader's lines methods returns a stream of all lines reader.lines().forEach(System.out::println); }
From source file:Test.java
public static void main(String[] args) { try (BufferedReader inputReader = Files.newBufferedReader(Paths.get(new URI("file:///C:/users.txt")), Charset.defaultCharset()); BufferedWriter outputWriter = Files.newBufferedWriter(Paths.get(new URI("file:///C:/users.bak")), Charset.defaultCharset())) { String inputLine;/*from w w w . j a v a2 s. co m*/ while ((inputLine = inputReader.readLine()) != null) { outputWriter.write(inputLine); outputWriter.newLine(); } System.out.println("Copy complete!"); } catch (URISyntaxException | IOException ex) { ex.printStackTrace(); } }
From source file:Test.java
public static void main(String[] args) { try (BufferedReader inputReader = Files.newBufferedReader(Paths.get(new URI("file:///C:/users.txt")), Charset.defaultCharset()); BufferedWriter outputWriter = Files.newBufferedWriter(Paths.get(new URI("file:///C:/users.bak")), Charset.defaultCharset())) { String inputLine;/*from www .j a v a 2 s .co m*/ while ((inputLine = inputReader.readLine()) != null) { outputWriter.write(inputLine); outputWriter.newLine(); } System.out.println("Copy complete!"); } catch (URISyntaxException | IOException ex) { ex.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) { Path wiki_path = Paths.get("C:/tutorial/wiki", "wiki.txt"); Charset charset = Charset.forName("UTF-8"); try (BufferedReader reader = Files.newBufferedReader(wiki_path, charset)) { String line = null;//w w w. j av a 2s. c o m while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.err.println(e); } }
From source file:Main.java
public static void main(String[] args) throws IOException { Path path = Paths.get("/home/docs/users.txt"); Charset charset = Charset.forName("ISO-8859-1"); try (BufferedReader reader = Files.newBufferedReader(path, charset)) { String line = null;//from ww w.ja va 2 s .c o m while ((line = reader.readLine()) != null) { System.out.println(line); } } }
From source file:net.cloudkit.enterprises.ws.SuperPassQueryTest.java
public static void main(String[] args) throws Exception { List<String> params = new ArrayList<>(); // System.out.println(SuperPassQueryTest.class.getResource("/list.dat").toURI()); Path path = Paths.get(SuperPassQueryTest.class.getResource("/list.dat").toURI()); try (BufferedReader reader = Files.newBufferedReader(path, Charset.forName("UTF-8"))) { // System.out.println(reader.readLine().length()); String line;// w w w .j a v a2s. c o m while ((line = reader.readLine()) != null) { // System.out.println("TEXT LINE:" + line); params.add(line); } } Path succeededFile = Paths.get(SuperPassQueryTest.class.getResource("/succeeded.dat").toURI()); BufferedWriter succeededWriter = Files.newBufferedWriter(succeededFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND); Path failedFile = Paths.get(SuperPassQueryTest.class.getResource("/failed.dat").toURI()); BufferedWriter failedWriter = Files.newBufferedWriter(failedFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND); for (String param : params) { try { /* StringTokenizer stringTokenizer = new StringTokenizer(param, ","); while(stringTokenizer.hasMoreTokens()){ System.out.println("COUNT:" + stringTokenizer.countTokens()); System.out.println("VALUE:" + stringTokenizer.nextToken()); System.out.println("COUNT:" + stringTokenizer.countTokens()); } */ System.out.println("QUERY PARAMS:" + param); String[] paramArray = param.split(","); // System.out.println("VALUE:" + paramArray[0]); // System.out.println("VALUE:" + paramArray[1]); // System.out.println("VALUE:" + paramArray[2]); String value_1 = paramArray[0]; String value_2 = paramArray[1]; String value_3 = paramArray[2]; String serviceName = "eport.superpass.spdec.DecQueryListService"; byte[] requestContext = ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n" + "<RequestContext>\n" + " <Group name=\"SystemInfo\">\n" + " <Key name=\"NAME_FULL\">???</Key>\n" + " <Key name=\"ClientId\">5300001976914</Key>\n" + " <Key name=\"CertNo\">df630b</Key>\n" + " <Key name=\"SaicSysNo\">766350979</Key>\n" + " <Key name=\"DEP_IN_CODE\">5300</Key>\n" + " <Key name=\"REG_CO_CGAC\">4403180237</Key>\n" + " <Key name=\"ENT_SEQ_NO\">000000000000315537</Key>\n" + " <Key name=\"ENT_TYPE\">3</Key>\n" + " <Key name=\"IcCode\">8930000011040</Key>\n" + " <Key name=\"OperatorName\">?</Key>\n" + " <Key name=\"DEP_CODE_CHG\">5305</Key>\n" + " <Key name=\"SessionId\">AE2533938D521A9972186B07BBBEB244</Key>\n" + " </Group>\n" + " <Group name=\"DataPresentation\">\n" + " <Key name=\"SignatureAlgorithm\"/>\n" + " <Key name=\"EncryptAlgorithm\"/>\n" + " <Key name=\"CompressAlgorithm\"/>\n" + " </Group>\n" + " <Group name=\"Default\">\n" + " <Key name=\"clientSystemId\">0400620001</Key>\n" + " <Key name=\"needWebInvoke\">True</Key>\n" + " </Group>\n" + "</RequestContext>").getBytes(); byte[] requestData = ("<?xml version=\"1.0\"?>\n" + "<DecQueryListRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" + " <OperType>0</OperType>\n" + " <DecType>\n" + " <TrnType>0</TrnType>\n" + " <IEFlag>" + value_3 + "</IEFlag>\n" + " <DecSubType />\n" + " </DecType>\n" + " <CopeCode>766350979</CopeCode>\n" + " <AgentCode>4403180237</AgentCode>\n" + " <SeqNo>" + value_1 + "</SeqNo>\n" + " <UserType>0</UserType>\n" + "</DecQueryListRequest>").getBytes(); Holder<byte[]> responseData = new Holder<>(); // <?xml version="1.0" encoding="UTF-8" standalone="no"?><ResponseContext><ResponseCode>0</ResponseCode><ResponseMessage>success</ResponseMessage><ServiceResponseCode>0</ServiceResponseCode><ServiceResponseMessage>?</ServiceResponseMessage><ExceptionDetail/><Group name="DataPresentation"><Key name="CompressAlgorithm"/><Key name="SignatureAlgorithm"/><Key name="EncryptAlgorithm"/></Group></ResponseContext> // <?xml version="1.0" encoding="UTF-8" standalone="yes"?><DecQueryListResponse><QueryResponseData><EntryId>531820161181010544</EntryId><SeqNo>000000001139524197</SeqNo><BillNo>2016051920160523</BillNo><IEDate>20160621</IEDate><TradeMode>0615</TradeMode><ItemsNum>19</ItemsNum><TrafName></TrafName><Status>O</Status><AgentName>???</AgentName><IEFlag>I</IEFlag><CustomsCode>5318</CustomsCode><DeclTrnRel>0</DeclTrnRel><RetExplain>;?</RetExplain><NoticeDate>2016-06-29</NoticeDate><TradeName>()??</TradeName><ExtendField><DecDeclareSysType>2</DecDeclareSysType><TrnSysType>1</TrnSysType><AssureExamRet>0</AssureExamRet><RelatedDocumentType> </RelatedDocumentType><DeclareSeqNo> </DeclareSeqNo><ExtendField53>P</ExtendField53><ExtendField>21 P</ExtendField></ExtendField><EntryType>M</EntryType></QueryResponseData></DecQueryListResponse> // String responseContext = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><ResponseContext><ResponseCode>0</ResponseCode><ResponseMessage>success</ResponseMessage><ServiceResponseCode>0</ServiceResponseCode><ServiceResponseMessage>?</ServiceResponseMessage><ExceptionDetail/><Group name=\"DataPresentation\"><Key name=\"CompressAlgorithm\"/><Key name=\"SignatureAlgorithm\"/><Key name=\"EncryptAlgorithm\"/></Group></ResponseContext>"; // String queryListResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><DecQueryListResponse><QueryResponseData><EntryId>531820161181010544</EntryId><SeqNo>000000001139524197</SeqNo><BillNo>2016051920160523</BillNo><IEDate>20160621</IEDate><TradeMode>0615</TradeMode><ItemsNum>19</ItemsNum><TrafName></TrafName><Status>O</Status><AgentName>???</AgentName><IEFlag>I</IEFlag><CustomsCode>5318</CustomsCode><DeclTrnRel>0</DeclTrnRel><RetExplain>;?</RetExplain><NoticeDate>2016-06-29</NoticeDate><TradeName>()??</TradeName><ExtendField><DecDeclareSysType>2</DecDeclareSysType><TrnSysType>1</TrnSysType><AssureExamRet>0</AssureExamRet><RelatedDocumentType> </RelatedDocumentType><DeclareSeqNo> </DeclareSeqNo><ExtendField53>P</ExtendField53><ExtendField>21 P</ExtendField></ExtendField><EntryType>M</EntryType></QueryResponseData></DecQueryListResponse>"; String responseContext = new String( superPass.service(serviceName, requestContext, requestData, responseData)); String queryListResponse = new String(responseData.value); System.out.println("RESPONSE_CONTEXT:" + responseContext); System.out.println("QUERY_LIST_RESPONSE:" + queryListResponse); String serviceResponseCode = parsingReceiptStatus(responseContext); System.out.println("SERVICE_RESPONSE_CODE:" + serviceResponseCode); if (serviceResponseCode.equals("0")) { String data = parsingReceiptData(queryListResponse); System.out.println("DATA:" + data); succeededWriter.write(data); succeededWriter.flush(); } else { failedWriter.write(param + "\n"); failedWriter.flush(); } Thread.sleep(6 * 1000); } catch (Exception e) { failedWriter.write(param + "\n"); failedWriter.flush(); } } succeededWriter.close(); failedWriter.close(); }
From source file:com.github.ansell.shp.SHPDump.java
public static void main(String... args) throws Exception { final OptionParser parser = new OptionParser(); final OptionSpec<Void> help = parser.accepts("help").forHelp(); final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required() .describedAs("The input SHP file"); final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class).required() .describedAs("The output directory to use for debugging files"); final OptionSpec<String> outputPrefix = parser.accepts("prefix").withRequiredArg().ofType(String.class) .defaultsTo("shp-debug").describedAs("The output prefix to use for debugging files"); final OptionSpec<File> outputMappingTemplate = parser.accepts("output-mapping").withRequiredArg() .ofType(File.class).describedAs("The output mapping template file if it needs to be generated."); final OptionSpec<Integer> resolution = parser.accepts("resolution").withRequiredArg().ofType(Integer.class) .defaultsTo(2048).describedAs("The output image file resolution"); final OptionSpec<String> format = parser.accepts("format").withRequiredArg().ofType(String.class) .defaultsTo("png").describedAs("The output image format"); final OptionSpec<String> removeIfEmpty = parser.accepts("remove-if-empty").withRequiredArg() .ofType(String.class).describedAs( "The name of an attribute to remove if its value is empty before outputting the resulting shapefile. Use multiple times to specify multiple fields to check"); OptionSet options = null;//from ww w . j av a 2 s. c o m try { options = parser.parse(args); } catch (final OptionException e) { System.out.println(e.getMessage()); parser.printHelpOn(System.out); throw e; } if (options.has(help)) { parser.printHelpOn(System.out); return; } final Path inputPath = input.value(options).toPath(); if (!Files.exists(inputPath)) { throw new FileNotFoundException("Could not find input SHP file: " + inputPath.toString()); } final Path outputPath = output.value(options).toPath(); if (!Files.exists(outputPath)) { throw new FileNotFoundException("Output directory does not exist: " + outputPath.toString()); } final Path outputMappingPath = options.has(outputMappingTemplate) ? outputMappingTemplate.value(options).toPath() : null; if (options.has(outputMappingTemplate) && Files.exists(outputMappingPath)) { throw new FileNotFoundException( "Output mapping template file already exists: " + outputMappingPath.toString()); } final Set<String> filterFields = ConcurrentHashMap.newKeySet(); if (options.has(removeIfEmpty)) { for (String nextFilterField : removeIfEmpty.values(options)) { System.out.println("Will filter field if empty value found: " + nextFilterField); filterFields.add(nextFilterField); } } if (!filterFields.isEmpty()) { System.out.println("Full set of filter fields: " + filterFields); } final String prefix = outputPrefix.value(options); FileDataStore store = FileDataStoreFinder.getDataStore(inputPath.toFile()); if (store == null) { throw new RuntimeException("Could not read the given input as an ESRI Shapefile: " + inputPath.toAbsolutePath().toString()); } for (String typeName : new LinkedHashSet<>(Arrays.asList(store.getTypeNames()))) { System.out.println(""); System.out.println("Type: " + typeName); SimpleFeatureSource featureSource = store.getFeatureSource(typeName); SimpleFeatureType schema = featureSource.getSchema(); Name outputSchemaName = new NameImpl(schema.getName().getNamespaceURI(), schema.getName().getLocalPart().replace(" ", "").replace("%20", "")); System.out.println("Replacing name on schema: " + schema.getName() + " with " + outputSchemaName); SimpleFeatureType outputSchema = SHPUtils.changeSchemaName(schema, outputSchemaName); List<String> attributeList = new ArrayList<>(); for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) { System.out.println("Attribute: " + attribute.getName().toString()); attributeList.add(attribute.getName().toString()); } CsvSchema csvSchema = CSVUtil.buildSchema(attributeList); SimpleFeatureCollection collection = featureSource.getFeatures(); int featureCount = 0; Path nextCSVFile = outputPath.resolve(prefix + ".csv"); Path nextSummaryCSVFile = outputPath .resolve(prefix + "-" + outputSchema.getTypeName() + "-Summary.csv"); List<SimpleFeature> outputFeatureList = new CopyOnWriteArrayList<>(); try (SimpleFeatureIterator iterator = collection.features(); Writer bufferedWriter = Files.newBufferedWriter(nextCSVFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); SequenceWriter csv = CSVUtil.newCSVWriter(bufferedWriter, csvSchema);) { List<String> nextLine = new ArrayList<>(); while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); featureCount++; if (featureCount <= 2) { System.out.println(""); System.out.println(feature.getIdentifier()); } else if (featureCount % 100 == 0) { System.out.print("."); } boolean filterThisFeature = false; for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) { String featureString = Optional.ofNullable(feature.getAttribute(attribute.getName())) .orElse("").toString(); nextLine.add(featureString); if (filterFields.contains(attribute.getName().toString()) && featureString.trim().isEmpty()) { filterThisFeature = true; } if (featureString.length() > 100) { featureString = featureString.substring(0, 100) + "..."; } if (featureCount <= 2) { System.out.print(attribute.getName() + "="); System.out.println(featureString); } } if (!filterThisFeature) { outputFeatureList.add(SHPUtils.changeSchemaName(feature, outputSchema)); csv.write(nextLine); } nextLine.clear(); } } try (Reader csvReader = Files.newBufferedReader(nextCSVFile, StandardCharsets.UTF_8); Writer summaryOutput = Files.newBufferedWriter(nextSummaryCSVFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); final Writer mappingWriter = options.has(outputMappingTemplate) ? Files.newBufferedWriter(outputMappingPath) : NullWriter.NULL_WRITER) { CSVSummariser.runSummarise(csvReader, summaryOutput, mappingWriter, CSVSummariser.DEFAULT_SAMPLE_COUNT, false); } if (featureCount > 100) { System.out.println(""); } System.out.println(""); System.out.println("Feature count: " + featureCount); SimpleFeatureCollection outputCollection = new ListFeatureCollection(outputSchema, outputFeatureList); Path outputShapefilePath = outputPath.resolve(prefix + "-" + outputSchema.getTypeName() + "-dump"); if (!Files.exists(outputShapefilePath)) { Files.createDirectory(outputShapefilePath); } SHPUtils.writeShapefile(outputCollection, outputShapefilePath); // Create ZIP file from the contents to keep the subfiles together Path outputShapefileZipPath = outputPath .resolve(prefix + "-" + outputSchema.getTypeName() + "-dump.zip"); try (final OutputStream out = Files.newOutputStream(outputShapefileZipPath, StandardOpenOption.CREATE_NEW); final ZipOutputStream zip = new ZipOutputStream(out, StandardCharsets.UTF_8);) { Files.list(outputShapefilePath).forEachOrdered(Unchecked.consumer(e -> { zip.putNextEntry(new ZipEntry(e.getFileName().toString())); Files.copy(e, zip); zip.closeEntry(); })); } try (final OutputStream outputStream = Files.newOutputStream( outputPath.resolve(prefix + "." + format.value(options)), StandardOpenOption.CREATE_NEW);) { MapContent map = new MapContent(); map.setTitle(prefix + "-" + outputSchema.getTypeName()); Style style = SLD.createSimpleStyle(featureSource.getSchema()); Layer layer = new FeatureLayer(new CollectionFeatureSource(outputCollection), style); map.addLayer(layer); SHPUtils.renderImage(map, outputStream, resolution.value(options), format.value(options)); } } }
From source file:org.apache.zeppelin.interpreter.InterpreterInfoSaving.java
public static InterpreterInfoSaving loadFromFile(Path file) throws IOException { LOGGER.info("Load interpreter setting from file: " + file); InterpreterInfoSaving infoSaving = null; try (BufferedReader json = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { JsonParser jsonParser = new JsonParser(); JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject(); infoSaving = InterpreterInfoSaving.fromJson(jsonObject.toString()); if (infoSaving != null && infoSaving.interpreterSettings != null) { for (InterpreterSetting interpreterSetting : infoSaving.interpreterSettings.values()) { interpreterSetting.convertPermissionsFromUsersToOwners(jsonObject .getAsJsonObject("interpreterSettings").getAsJsonObject(interpreterSetting.getId())); }/*w w w .j a va 2s . co m*/ } } return infoSaving == null ? new InterpreterInfoSaving() : infoSaving; }
From source file:Util.java
/** * Read a file from disk as a list of String * @param filepath path on disk// w w w . ja v a 2 s . c o m * @return List of String */ public static List<String> readLinesFromFile(String filepath) { try { BufferedReader reader = Files.newBufferedReader(FileSystems.getDefault().getPath("", filepath), Charset.defaultCharset()); List<String> lines = new ArrayList<String>(); String line = null; while ((line = reader.readLine()) != null) lines.add(line); return lines; } catch (IOException ioe) { ioe.printStackTrace(); } return null; }
From source file:io.grpc.alts.CheckGcpEnvironment.java
private static boolean isRunningOnGcp() { try {//from ww w.j a va2 s . c o m if (SystemUtils.IS_OS_LINUX) { // Checks GCE residency on Linux platform. return checkProductNameOnLinux(Files.newBufferedReader(Paths.get(DMI_PRODUCT_NAME), UTF_8)); } else if (SystemUtils.IS_OS_WINDOWS) { // Checks GCE residency on Windows platform. Process p = new ProcessBuilder().command(WINDOWS_COMMAND, "Get-WmiObject", "-Class", "Win32_BIOS") .start(); return checkBiosDataOnWindows(new BufferedReader(new InputStreamReader(p.getInputStream(), UTF_8))); } } catch (IOException e) { logger.log(Level.WARNING, "Fail to read platform information: ", e); return false; } // Platforms other than Linux and Windows are not supported. return false; }