用Java代码创建一个文件并写进数据<需要改进流>
代码中有注释,自己看吧。
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
* The <code>PACKAGE_NAME.Demo</code> class have to be described
* 给一个文件中写数据
* @author dujlc
* @date 2021/9/10 16:46
* @see
* @since 1.0
*/
public class DemoTest {
/**
* 需要重复写入文件的内容重复的次数
*/
private static int COUNT = 100;
/**
* 需要重复写入文件的内容
*/
private static String CONTENT = "时间飞快的流逝。\n";
/**
* 需要生成文件的路径以及文件名称
*/
private static String FILE_PATH = "E:/myFile.txt";
/**
* 本次 IO 操作需要用到的字符集
*/
private static String CHARACTER = "UTF-8";
/**
* 这块的概念还不是很清楚,后续需要再学习
* 将字符流转换成字节流输入(链接需要输入文字所用的流)
*/
private static OutputStreamWriter OSW = null;
/**
* 这块的概念还不是很清楚,后续需要再学习
* 将数据写进文件所用的流(链接需要输入到文件中所用的流)
*/
private static FileOutputStream FOS = null;
@Test
public void doWrite() throws IOException {
// new出一个文件对象,因为查找或者创建文件都需要用文件对象去操作
File file = new File(FILE_PATH);
// 如果没有该路径下没有该文件,则创建一个
if (!file.exists()) {
file.createNewFile();
}
// OutputStreamWriter向文件写入内容
writeByOutputStreamWrite();
}
/**
* 用OutputStreamWrite向文件写入内容
* @throws IOException 抛出检查型 IO异常
*/
private void writeByOutputStreamWrite() throws IOException {
try {
FOS = new FileOutputStream(FILE_PATH);
OSW = new OutputStreamWriter(FOS, CHARACTER);
for(int index = 0;index < COUNT;index++) {
OSW.write(CONTENT);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
closeStream();
}
}
/**
* 关闭流
* @throws IOException 抛出检查型 IO异常
*/
private void closeStream() throws IOException {
if (OSW != null) {
OSW.close();
OSW = null;
}
if (FOS != null) {
FOS.close();
FOS = null;
}
}
}