本篇介绍文件的IO操作。下面这张图清晰地描述了关于IO流操作的API。
这里介绍其中一种:FileOutputStream和FileInputStream。
package com.example.javatest;
import java.io.*;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Author:W
* 文件操作
* 1.目录的操作
* 2.文件操作:创建、文件流输入输出
*/
public class MainTest {
public static void main(String[] args)
{
System.out.println("===文件夹创建===");
//文件夹检查创建:mkdirs创建一个文件夹和它的所有父文件夹
String dirName = "G:/JavaTest/LocalFiles/Test";
File dir = new File(dirName);
dir.mkdirs();
try
{
System.out.println("===文件创建输出===");
//文件的创建
String fileName = dirName+"/HelloWorld.txt";
File file1 = new File(fileName);
//创建文件输出流
FileOutputStream fileOutStream = new FileOutputStream(file1);
//创建写入流,并指定编码
OutputStreamWriter writer = new OutputStreamWriter(fileOutStream, "UTF-8");
System.out.println("文件写入:"+"Hello World!");
writer.write("Hello World!");
writer.flush();
writer.close();
fileOutStream.close();
System.out.println("===文件输入===");
//创建文件输入流
FileInputStream fileInputStream = new FileInputStream(file1);
//创建文件读取流,并指定编码
InputStreamReader reader = new InputStreamReader(fileInputStream, "UTF-8");
//创建接收字符缓冲对象
StringBuffer sb = new StringBuffer();
while (reader.ready()) {
sb.append((char) reader.read());
}
System.out.println("文件读取输出字符串:"+sb.toString());
reader.close();
fileInputStream.close();
}catch (IOException e)
{
System.out.println("文件创建异常Error:"+e.toString());
}
}
}
运行输出结果如下: