public class Hello {
public static void main(String[] args) {
System.out.println(“Hello World”);
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class MyCat {
// 1. 参数中有文件路径,把路径对应文件的内容显示到标准输出上
// 2. 参数中没有文件路径,直接从标准输入上读取文件,显示到标准输出上
public static void main(String[] args) throws IOException {
InputStream is;
if (args.length > 0) {
// 有参数
System.out.println("MyCat: 从文件内容读");
String path = args[0];
is = new FileInputStream(path);
} else {
// 没有参数
System.out.println("MyCat: 从标准输入读");
is = System.in;
}
Scanner scanner = new Scanner(is, "UTF-8");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
// 待修改:应该把自己打开的资源关闭的
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class MyGrep {
// 至少有一个参数,匹配那个字符串
// 如果只有一个参数,从标准输入中找匹配
// 如果有两个参数,从第二个参数对应的路径内容中找匹配
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println(“必须带着参数”);
return;
}
String substring = args[0];
InputStream is;
if (args.length == 1) {
System.out.println("MyGrep: 从标准输入读");
is = System.in;
} else {
System.out.println("MyGrep: 从文件内容读");
String path = args[1];
is = new FileInputStream(path);
}
Scanner scanner = new Scanner(is, "UTF-8");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains(substring)) {
System.out.println(line);
}
}
}
}