Java IO流应用场景编程
序言
Java提供了丰富的字节流基类InputStream和OutputStream的子类,字符流Reader和Writer的子类,以适应不同应用场景。在实际使用Java IO时需要对各种IO流进行组合以适应场景需要。
应用场景
1. 从键盘获取用户输入 Employee e = new Employee();
System.out.println("Please input Employee name:");
Scanner in = new Scanner(System.in);
String name = in.nextLine();
System.out.println("Please input Employee salary:");
double salary = in.nextDouble();
System.out.println("Please input Employee hireday yymmdd:");
int year = in.nextInt();
int month = in.nextInt();
int dayOfMonth = in.nextInt();
2. 文件拷贝
public class FileCopyText {
public static void main(String[] args) {
int temp = 0;
// TODO Auto-generated method stub
try {
FileInputStream in = new FileInputStream("mF.BMP");
FileOutputStream out = new FileOutputStream("mFCopy.BMP", true);
while((temp = in.read()) != -1) {
out.write(temp);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
3. Java基本数据类型保存到文件
DataOutputStream作为装饰类,配合文件输出流,可以方便的将Java基本数据类型数据保持到文件。
public static void WriteEmploy(Employee employee, DataOutputStream out) {
try {
out.writeChars(employee.getName());
out.writeDouble(employee.getSalary());
out.writeInt(employee.getHireDay().getYear());
out.writeInt(employee.getHireDay().getMonthValue());
out.writeInt(employee.getHireDay().getDayOfMonth());
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
Employee employee = readEmploy(in);
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("testfile"));
WriteEmploy(employee, out);
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
4.文本类型数据保存
PrintWriter(public class PrintWriter extends Writer)
可用来创建一个文件并向文本文件写入数据,支持基础数据类型数据写。
PrintWriter常用方法
public PrintWriter(Writer out,boolean autoFlush) | 构造方法 | |
---|---|---|
public void print(char c) | 普通方法 | 向文件写入一个字符 |
public void print(int i) | 普通方法 | 向文件写入一个整数 |
public void print(long l) | 普通方法 | 向文件写入一个long数据 |
public void print(float f) | 普通方法 | 向文件写入一个单精度浮点数 |
public void print(double d) | 普通方法 | 向文件写入一个双精度浮点数 |
public void print(String s) | 普通方法 | 向文件写入一个字符串 |
public static void writeEmployeeData(Employee employee, PrintWriter out)
{
out.println(employee.getName() + "|" + employee.getSalary() + "|" + employee.getHireDay().toString());
return;
}
public static void main(String[] args) {
Employee employee = readEmploy(new Scanner(System.in));
try(PrintWriter out = new PrintWriter("employee.txt","UTF-8")) {
writeEmployeeData(employee, out);
}catch (IOException e) {
e.printStackTrace();
}
}