aboutsummaryrefslogtreecommitdiffhomepage
path: root/examples/java-native/src/main/java/com/example/myproject/Greeter.java
blob: 9ab657afc9ae079a2a78509e4a7a71f626109d55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.example.myproject;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;

/**
 * Prints a greeting which can be customized by building with resources and/or passing in command-
 * line arguments.
 *
 * <p>Building and running this file will print "Hello world". Build and run the
 * //examples/java-native/src/main/java/com/example/myproject:hello-world target to demonstrate
 * this.</p>
 *
 * <p>If this is built with a greeting.txt resource included, it will replace "Hello" with the
 * contents of greeting.txt. The
 * //examples/java-native/src/main/java/com/example/myproject:hello-resources target demonstrates
 * this.</p>
 *
 * <p>If arguments are passed to the binary on the command line, the first argument will replace
 * "world" in the output. See //examples/java-native/src/test/java/com/example/myproject:hello's
 * argument test.</p>
 */
public class Greeter {
  static PrintStream out = System.out;

  public static String convertStreamToString(InputStream is) throws Exception {
    try (Scanner s = new Scanner(is)) {
      s.useDelimiter("\n");
      return s.hasNext() ? s.next() : "";
    }
  }

  public void hello(String obj) throws Exception {
    String greeting = "Hello";
    InputStream stream  = Greeter.class.getResourceAsStream("/greeting.txt");
    if (stream != null) {
      greeting = convertStreamToString(stream).trim();
    }
    out.println(greeting + " " + obj);
  }

  public static void main(String... args) throws Exception {
    Greeter g = new Greeter();
    String obj = args.length > 0 ? args[0] : "world";
    g.hello(obj);
  }
}