您的位置:首页 > 编程语言 > Java开发

Example of Unix commands implemented in Java

2014-10-10 00:29 393 查看
I created some illustrative and simple implementations of common Unix commands. For those who are familiar with Unix-like systems them make easier to understand Java. For those who are familiar with Java them make easier to understand Unix-like systems. :-)

1. PWD

The first one is pwd that show the current working directory.

public class Jpwd {
public static void main(String[] args) {
String pwd = System.getProperty("user.dir");
System.out.println(pwd);
}
}


Running this at /home/silveira directory gives us as output:

$ java Jpwd
/home/silveira

1. CAT

The command cat is usually utilized for displaying files.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Jcat {
public static void main(String[] args) {
if(args.length==1){
try {
FileReader fileReader = new FileReader(args[0]);
BufferedReader in = new BufferedReader(fileReader);
String line;
while((line = in.readLine())!= null){
System.out.println(line);
}
} catch (FileNotFoundException ex) {
System.out.println(args[0]+", file not found.");
}
catch (IOException ex) {
System.out.println(args[0]+", input/output error.");
}
}
}
}

$ java Jcat /etc/timezone
America/Fortaleza

3. LS

The command ls is to list files. The File API (java.io.File) is very flexible and portable, but in this
example I want just list files and directories of the current directory.

import java.io.File;

public class Jls {
public static void main(String[] args) {
File dir = new File(System.getProperty("user.dir"));
String childs[] = dir.list();
for(String child: childs){
System.out.println(child);
}
}
}


Usage:

$ java Jpwd
/home/silveira/example
$ java Jls
directoryA
fileA
.somefile

4. CD

The cd command changes the current working directory.

import java.io.File;

public class Jcd {
public static void main(String[] args) {
if(args.length==1){
File dir = new File(args[0]);
if(dir.isDirectory()==true) {
System.setProperty("user.dir", dir.getAbsolutePath());
} else {
System.out.println(args[0] + "is not a directory.");
}
}
}
}

Usage:

$ java Jpwd

/home/silveira

$ java Jcd /tmp

$ java Jpwd

/tmp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: