<SPAN style="FONT-SIZE: 16px">package demo.others;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Formatter;
/**
* Formatter类用于格式化
*
* @author Touch
*
*/
public class FormatterDemo {
public static void main(String[] args) {
int i = 1;
double d = 2.2352353456345;
// 1.两种最简单的格式化输出,类似c语言中的printf函数
System.out.format("%-3d%-5.3fn",i,d);
System.out.printf("%-3d%-5.3fn",d);
// Formatter类的使用
// 2.格式化输出到控制台
Formatter f = new Formatter(System.out);
f.format("%-3d%-8.2f%-10sn",d,"touch");
// 3.格式化输出到文件
Formatter ff = null;
try {
ff = new Formatter(new PrintStream("file/formater.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ff.format("%-3d%-8.2f%-10sn","touch");
// 4.String.format().同c语言中sprintf()
System.out.println(String.format("(%d%.2f%s)","touch"));
}
}
</SPAN>
<SPAN style="FONT-SIZE: 16px">package mine.util.others;
/**
* 以十六进制查看二进制文件
*/
public class Hex {
public static String format(byte[] data) {
StringBuilder result = new StringBuilder();
int n = 0;
for (byte b : data) {
if(n%16==0)
result.append(String.format("%05x: ",n));
result.append(String.format("%02x ",b));
n++;
if(n%16==0)
result.append('n');
}
return result.toString();
}
}
</SPAN>