Example usage for java.nio.charset Charset defaultCharset

List of usage examples for java.nio.charset Charset defaultCharset

Introduction

In this page you can find the example usage for java.nio.charset Charset defaultCharset.

Prototype

Charset defaultCharset

To view the source code for java.nio.charset Charset defaultCharset.

Click Source Link

Usage

From source file:com.mirth.connect.connectors.file.filesystems.test.FileConnectionTest.java

@Test
public void testWriteFile() {
    String testString = new String("This is just a test string");
    byte[] byteTest = testString.getBytes(Charset.defaultCharset());

    File testFile = new File("writeFile" + System.currentTimeMillis() + ".dat");

    try {/*from ww w .  ja v  a  2 s  .  c om*/
        fc.writeFile(testFile.getName(), someFolder.getAbsolutePath(), false,
                new ByteArrayInputStream(byteTest));
    } catch (Exception e) {
        fail("The FileConnection threw an exception, it should not have.");
    }

    File checkFile = new File(someFolder.getAbsolutePath() + File.separator + testFile.getName());

    // Now we load it back and check!
    try {
        byte[] verifyArr = FileUtils.readFileToByteArray(checkFile);
        assertArrayEquals(byteTest, verifyArr);
    } catch (Exception e) {
        fail("The JavaIO threw an exception (" + e.getClass().getName() + "): " + e.getMessage());
    }

    // Verify that appending works
    try {
        fc.writeFile(testFile.getName(), someFolder.getAbsolutePath(), true,
                new ByteArrayInputStream(byteTest));
    } catch (Exception e) {
        fail("The FileConnection threw an exception, it should not have (when appending).");
    }

    // Now we load it back and check!
    try {
        byte[] doubleCheck = new byte[byteTest.length * 2];
        System.arraycopy(byteTest, 0, doubleCheck, 0, byteTest.length);
        System.arraycopy(byteTest, 0, doubleCheck, byteTest.length, byteTest.length);

        byte[] verifyArr = FileUtils.readFileToByteArray(checkFile);
        assertArrayEquals(doubleCheck, verifyArr);
    } catch (Exception e) {
        fail("The JavaIO threw an exception (" + e.getClass().getName() + "): " + e.getMessage());
    }

}

From source file:com.fpuna.preproceso.PreprocesoTS.java

/**
 * Metodo estatico que lee el archivo y lo carga en una estructura de hash
 *
 * @param Archivo path del archivo//w ww  .j ava 2s . c  om
 * @return Hash con las sessiones leida del archivo de TrainigSet
 */
public static HashMap<String, SessionTS> leerArchivo(String Archivo, String sensor) {

    HashMap<String, SessionTS> SessionsTotal = new HashMap<String, SessionTS>();
    HashMap<String, String> actividades = new HashMap<String, String>();
    Path file = Paths.get(Archivo);

    if (Files.exists(file) && Files.isReadable(file)) {

        try {
            BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());

            String line;
            int cabecera = 0;

            while ((line = reader.readLine()) != null) {
                if (line.contentEquals("statusId | label")) {

                    //Leo todos las actividades  
                    while ((line = reader.readLine()) != null
                            && !line.contentEquals("statusId|sensorName|value|timestamp")) {
                        String part[] = line.split("\\|");
                        actividades.put(part[0], part[1]);
                        SessionTS s = new SessionTS();
                        s.setActividad(part[1]);
                        SessionsTotal.put(part[0], s);
                    }
                    line = reader.readLine();
                }

                String lecturas[] = line.split("\\|");

                if (lecturas[1].contentEquals(sensor)) {
                    Registro reg = new Registro();
                    reg.setSensor(lecturas[1]);
                    String[] values = lecturas[2].split("\\,");

                    if (values.length == 3) {
                        reg.setValor_x(Double.parseDouble(values[0].substring(1)));
                        reg.setValor_y(Double.parseDouble(values[1]));
                        reg.setValor_z(Double.parseDouble(values[2].substring(0, values[2].length() - 1)));
                    } else if (values.length == 5) {
                        reg.setValor_x(Double.parseDouble(values[0].substring(1)));
                        reg.setValor_y(Double.parseDouble(values[1]));
                        reg.setValor_z(Double.parseDouble(values[2]));
                        reg.setM_1(Double.parseDouble(values[3]));
                        reg.setM_2(Double.parseDouble(values[4].substring(0, values[4].length() - 1)));
                    }

                    reg.setTiempo(new Timestamp(Long.parseLong(lecturas[3])));

                    SessionTS s = SessionsTotal.get(lecturas[0]);
                    s.addRegistro(reg);
                    SessionsTotal.replace(lecturas[0], s);
                }
            }
        } catch (IOException ex) {
            System.err.println("Okapu");
            Logger.getLogger(PreprocesoTS.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    return SessionsTotal;
}

From source file:amp.lib.io.db.Database.java

/**
 * Executes the SQL in the supplied files. See 'getAllSQLFiles' for execution order of files.
 * Each file may have zero or more SQL statements, each terminated by a non-escaped ';' at the
 * end of the line.//w w w. j  a  v  a 2s .co m
 * @param sqlFiles the SQL files and directories
 */
public void buildSQL(List<File> sqlFiles) {
    for (File f : getAllSQLFiles(sqlFiles)) {
        try {
            String sql = FileUtils.readFileToString(f, Charset.defaultCharset());
            String[] statements = sql.split(";");
            for (String statement : statements) {
                execute(statement);
            }
        } catch (Exception e) {
            Report.error(e.getMessage());
        }
    }
}

From source file:com.qubole.rubix.core.TestCachingInputStream.java

private void testCachingHelper() throws IOException {
    inputStream.seek(100);/*from  ww  w. j  av  a2 s .c  o  m*/
    byte[] buffer = new byte[1000];
    int readSize = inputStream.read(buffer, 0, 1000);
    String output = new String(buffer, Charset.defaultCharset());
    String expectedOutput = DataGen.generateContent().substring(100, 1100);
    assertions(readSize, 1000, buffer, expectedOutput);
}

From source file:ccm.pay2spawn.configurator.HTMLGenerator.java

public static String readFile(File file) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(file.toURI()));
    return Charset.defaultCharset().decode(ByteBuffer.wrap(encoded)).toString();
}

From source file:downloadwebpages.DownloadWebpages.java

/**
 * read the webpages in the text file and save them in the java list
 *//*from  ww  w.j  a v a2 s  . c om*/
private void getWebpagesFromFile() {
    try {
        System.out.println("Reading: " + webpagesTxtFilePath);
        webpages = new ArrayList<>(); // initialize list

        Stream<String> stream = Files.lines(Paths.get(webpagesTxtFilePath), Charset.defaultCharset());
        stream.forEach((line) -> {
            System.out.println("Read line: " + line);
            String[] split = line.split("\\t");
            if (split.length > 1) {
                webpages.add(new Pair(split[0], split[1]));
            }
        });
        //stream.forEach(System.out::println); // print line from file
    } catch (IOException ex) {
        Logger.getLogger(DownloadWebpages.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.langmi.spring.batch.examples.readers.file.gzip.GZipBufferedReaderFactoryTest.java

@Test
public void testDefaultWithNormalFile() throws Exception {
    // try to create 
    BufferedReader reader = gzbrf.create(new FileSystemResource(PATH_TO_UNCOMPRESSED_TEST_FILE),
            Charset.defaultCharset().name());
    // creation successful?
    assertNotNull(reader);/*from  w  ww. ja va 2  s  . co m*/
    // clean up, close the reader
    reader.close();
}

From source file:com.guilin.flume.ng.source.rocketmq.RocketMQSource.java

@Override
public Status process() throws EventDeliveryException {
    List<Event> eventList = Lists.newArrayList();
    Map<MessageQueue, Long> offsetMap = Maps.newHashMap();

    try {//from  w  w w. ja  va 2  s  . c  om
        Set<MessageQueue> mqs = Preconditions.checkNotNull(consumer.fetchSubscribeMessageQueues(topic));
        for (MessageQueue mq : mqs) {
            // ?offset
            long offset = consumer.fetchConsumeOffset(mq, false);
            offset = offset < 0 ? 0 : offset;
            PullResult pullResult = consumer.pull(mq, tags, offset, maxNums);
            // ??Event
            if (pullResult.getPullStatus() == PullStatus.FOUND) {
                for (MessageExt messageExt : pullResult.getMsgFoundList()) {
                    Event event = new SimpleEvent();
                    Map<String, String> headers = new HashMap<String, String>();
                    headers.put(topicHeaderName, messageExt.getTopic());
                    headers.put(tagsHeaderName, messageExt.getTags());

                    //timestamp
                    String body = new String(messageExt.getBody(), Charset.defaultCharset());
                    Map<String, Object> map = JSON.parseObject(body, Map.class);
                    if (map.containsKey("timestamp")) {
                        headers.put("timestamp", map.get("timestamp").toString());
                    } else {
                        headers.put("timestamp", System.currentTimeMillis() + "");
                    }

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("MessageQueue={}, Topic={}, Tags={}, Message: {}", new Object[] { mq,
                                messageExt.getTopic(), messageExt.getTags(), messageExt.getBody() });
                    }
                    event.setBody(messageExt.getBody());
                    event.setHeaders(headers);
                    eventList.add(event);
                }
                offsetMap.put(mq, pullResult.getNextBeginOffset());
            }
        }

        if (CollectionUtils.isNotEmpty(eventList)) {
            // ??
            getChannelProcessor().processEventBatch(eventList);
            for (Map.Entry<MessageQueue, Long> entry : offsetMap.entrySet()) {
                // offset
                consumer.updateConsumeOffset(entry.getKey(), entry.getValue());
            }
        }

    } catch (Exception e) {
        LOG.error("RocketMQSource consume message exception", e);
        return Status.BACKOFF;
    }
    return Status.READY;
}

From source file:com.fns.grivet.service.NamedQueryServiceSelectTest.java

@Test
public void testCreateThenGetIncorrectParamsSupplied() throws IOException {
    Assertions.assertThrows(IllegalArgumentException.class, () -> {
        Resource r = resolver.getResource("classpath:TestSelectQuery.json");
        String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        NamedQuery namedQuery = objectMapper.readValue(json, NamedQuery.class);
        namedQueryService.create(namedQuery);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("timedCreated", LocalDateTime.now().plusDays(1).toString());
        namedQueryService.get("getAttributesCreatedBefore", params);
    });/*  www.ja  v a  2s.  com*/
}

From source file:edu.rit.flick.util.FlickTest.java

@Test
public void helpFlag() throws IOException {
    outContent.flush();//from  w w  w  .j a va 2s  .  c  o m
    outContent.reset();

    Flick.main(HELP_FLAG);
    String expectedUsageStatement = Files.toString(new File(RESOURCES_FOLDER + Flick.FLICK_USAGE_FILE),
            Charset.defaultCharset());
    String actualUsageStatement = outContent.toString();
    assertEquals(expectedUsageStatement, actualUsageStatement);

    outContent.flush();
    outContent.reset();

    Unflick.main(HELP_FLAG);
    expectedUsageStatement = Files.toString(new File(RESOURCES_FOLDER + Unflick.UNFLICK_USAGE_FILE),
            Charset.defaultCharset()) + "\n";
    actualUsageStatement = outContent.toString();
    assertEquals(expectedUsageStatement, actualUsageStatement);

    outContent.flush();
    outContent.reset();
}