Example usage for java.lang String format

List of usage examples for java.lang String format

Introduction

In this page you can find the example usage for java.lang String format.

Prototype

public static String format(Locale l, String format, Object... args) 

Source Link

Document

Returns a formatted string using the specified locale, format string, and arguments.

Usage

From source file:Main.java

public static void main(String[] args) {

    Calendar now = Calendar.getInstance();
    Date nowDate = now.getTime();

    long twoHoursByMillis = 2 * HOUR;
    long thirtyMinutesByMillis = 30 * MINUTE;

    Date twoHoursAndThirtyMinutesFromNow = new Date(twoHoursByMillis + thirtyMinutesByMillis);
    System.out.println(String.format("now %s and later %s", nowDate, twoHoursAndThirtyMinutesFromNow));

    long ms = 10304004543l;
    StringBuilder text = new StringBuilder("");
    if (ms > DAY) {
        text.append(ms / DAY).append(" days ");
        ms %= DAY;/*from   www. java 2  s. c o  m*/
    }
    if (ms > HOUR) {
        text.append(ms / HOUR).append(" hours ");
        ms %= HOUR;
    }
    if (ms > MINUTE) {
        text.append(ms / MINUTE).append(" minutes ");
        ms %= MINUTE;
    }
    if (ms > SECOND) {
        text.append(ms / SECOND).append(" seconds ");
        ms %= SECOND;
    }
    text.append(ms + " ms");
    System.out.println(text.toString());
}

From source file:Main.java

public static void main(String[] args) {
    Set<String> allZones = ZoneId.getAvailableZoneIds();
    List<String> zoneList = new ArrayList<String>(allZones);
    Collections.sort(zoneList);/* w  ww . j  a va2  s . co  m*/

    LocalDateTime dt = LocalDateTime.now();
    for (String s : zoneList) {
        ZoneId zone = ZoneId.of(s);
        ZonedDateTime zdt = dt.atZone(zone);
        ZoneOffset offset = zdt.getOffset();
        String out = String.format("%35s %10s%n", zone, offset);
        System.out.println(out);
    }
}

From source file:Main.java

public static void main(String[] args) throws java.lang.Exception {
    String[] StartTimes = { "10:00", "7:00" };
    String[] EndTimes = { "12:00", "14:56" };
    for (int i = 0; i < StartTimes.length; i++) {
        if (StartTimes != null && StartTimes.length > 0 && EndTimes != null && EndTimes.length > 0) {
            SimpleDateFormat format = new SimpleDateFormat("HH:mm");
            Date date1 = format.parse(StartTimes[i]);
            Date date2 = format.parse(EndTimes[i]);
            long millis = date2.getTime() - date1.getTime();

            String hourminute = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis)
                            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)));
            System.out.println(hourminute);
        }/*from   w  w w .  j ava 2  s . c  o  m*/
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection con = DriverManager.getConnection("jdbc:h2:mem:");
    Statement s = con.createStatement();
    s.execute("CREATE TABLE Table1 (Column1 CLOB)");

    InputStream is = new FileInputStream("data.txt");
    Reader rdr = new InputStreamReader(is, StandardCharsets.ISO_8859_1);
    PreparedStatement ps = con.prepareStatement("INSERT INTO Table1 (Column1) VALUES (?)");
    ps.setCharacterStream(1, rdr);/*  www  . j  a  v  a2s  .  c  o m*/
    ps.executeUpdate();

    ResultSet rs = s.executeQuery("SELECT Column1 FROM Table1");
    int rowNumber = 0;
    while (rs.next()) {
        String str = rs.getString("Column1");
        System.out.println(String.format("Row %d: CLOB is %d character(s) long.", ++rowNumber, str.length()));
    }
    rs.close();
    con.close();
}

From source file:be.dnsbelgium.rdap.client.ManGenerator.java

public static void main(String[] args) {
    Options options = new RDAPOptions(Locale.ENGLISH);
    Iterator<Option> it = options.getOptions().iterator();
    StringBuilder sb = new StringBuilder();
    while (it.hasNext()) {
        Option option = it.next();
        sb.append(String.format(".IP \"%s\"\n%s\n", getOptionString(option),
                option.getDescription() == null ? "" : option.getDescription()));
    }/* w  w w .  j av  a  2s.c  om*/
    System.out.println(sb.toString());
}

From source file:de.britter.beyondstringutils.CsvExample.java

public static void main(String[] args) throws Exception {
    InputStream is = CsvExample.class.getResourceAsStream("heros.csv");
    Iterable<CSVRecord> records = CSVFormat.DEFAULT.withHeader("First Name", "Last Name").withSkipHeaderRecord()
            .parse(new InputStreamReader(is));

    for (CSVRecord record : records) {
        String firstName = record.get("First Name");
        String lastName = record.get("Last Name");
        System.out.println(String.format("First Name: %s; Last Name: %s", firstName, lastName));
    }//  w  w w.ja va 2s  . co m

}

From source file:com.apress.prospringintegration.corespring.aop.MainAOP.java

public static void main(String[] args) throws Exception {

    ApplicationContext app = new ClassPathXmlApplicationContext("ioc_aop.xml");
    PurchaseOrderProcessor orderProcessor = app.getBean(PurchaseOrderProcessor.class);

    PurchaseOrder order = new PurchaseOrder();
    order.setItemCost(1000.00f);/*from  ww w . j av a 2s  . com*/
    Receipt receipt = orderProcessor.processPurchaseOrder(order);

    PurchaseOrderDiscountProcessor orderDiscountProcessor = (PurchaseOrderDiscountProcessor) orderProcessor;
    Receipt discountedReceipt = orderDiscountProcessor.processDiscountOrder(order,
            DiscountStrategy.HALF_OFF_ENTIRE);

    System.out.println(String.format("Total discounted purchase amount (given %s discount): %f ",
            DiscountStrategy.HALF_OFF_ENTIRE,
            (discountedReceipt.getPurchaseAmt() - discountedReceipt.getDiscountedAmount())));
}

From source file:com.apress.prospringintegration.webservice.client.TicketWebServiceDomClient.java

public static void main(String[] args) throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("client.xml");

    MessageChannel channel = context.getBean("ticketRequests", MessageChannel.class);

    String body = String.format(bodyTemplate, "Message Broker Down", "emergency");
    System.out.println(body);//from  ww  w  .ja  v  a  2 s  .  c  om
    MessagingTemplate messagingTemplate = new MessagingTemplate();
    Message<?> message = messagingTemplate.sendAndReceive(channel, MessageBuilder.withPayload(body).build());

    System.out.println(message.getPayload());

}

From source file:de.tudarmstadt.ukp.dkpro.core.mallet.lda.util.PrintTopWords.java

public static void main(String[] args) throws IOException {
    setOptions(args);//from  ww w .j  a  v  a  2s.  com
    String targetFile = modelFile + TARGET_FILE_SUFFIX;
    LOG.info(String.format("%nReading model from '%s'.%nStoring topic words in '%s'.", modelFile, targetFile));

    ParallelTopicModel model;
    try {
        model = ParallelTopicModel.read(modelFile);
    } catch (Exception e) {
        throw new IOException(e);
    }
    model.printTopWords(new File(targetFile), nWords + 1, false);
}

From source file:com.javacreed.examples.flyway.Example2.java

public static void main(final String[] args) {
    Example2.LOGGER.debug("Loading the spring context");
    try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/META-INF/application-context.xml")) {
        final JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);

        Example2.LOGGER.debug("Name      | Surname");
        Example2.LOGGER.debug("-----------------------");
        jdbcTemplate.query("SELECT * FROM `sample_table`", new RowCallbackHandler() {
            @Override/*  ww  w  . ja va  2s  .  c o m*/
            public void processRow(final ResultSet resultSet) throws SQLException {
                Example2.LOGGER.debug(String.format("%-10s| %-10s", resultSet.getString("name"),
                        resultSet.getString("surname")));
            }
        });
        Example2.LOGGER.debug("-----------------------");
    }
}