package com.lijy.util;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileUtilTest {
/** logger */
protected static Logger log = Logger.getLogger(FileUtilTest.class);
@Test
public void testWriteFile() throws IOException {
String path = "D:\\settledown";
String fileName = "test.txt";
String content = "Hello World! 你好,世界";
String charset = "GBK";
String filePath = writeFile(path, fileName, content, charset);
System.out.println(filePath);
}
@Test
public void testRead(){
File file = new File("D:\\settledown\\test.txt");
String str = read(file);
System.out.println(str);
}
/**
* 读文件
*
* @param file
* @return
*/
public static String read(File file) {
StringBuffer contents = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
} catch (FileNotFoundException e) {
log.info("下载文件失败");
e.printStackTrace();
}
try {
log.info("文件路径" + file.getAbsolutePath());
String line = null;
while ((line = br.readLine()) != null) {
contents.append(line).append("\r\n");
}
br.close();
log.info("文件内容" + contents.toString());
} catch (IOException e) {
e.printStackTrace();
}
return contents.toString();
}
/**
*
* @param path 自定义文件路径
* @param fileName 自定义文件名
* @param content 组装文件内容
* @param charset 文件编码方式
* @return
*/
public static String writeFile(String path, String fileName, String content, String charset) throws IOException {
mkDir(path);
String filePath = path + File.separator + fileName;//D:\settledown\test.txt
File file = new File(filePath);
if (file.exists()) {//如果文件存在,那么删除
file.delete();
}
file.createNewFile();//创建文件
FileOutputStream fops = new FileOutputStream(file);
fops.write((content).getBytes(charset));
fops.flush();
fops.close();
return filePath;
}
/**
* @param path 路径
*/
public static void mkDir(String path) {
File file = new File(path);
if (!file.exists()) {//如果目录不存在
file.mkdirs();
}
}
/**性能上没有read(File file)方法好*/
public static String readFile(String filePath) throws IOException
{
File file = new File(filePath);
FileInputStream fin = new FileInputStream(file);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
while (true)
{
int read = fin.read();
if (read == -1)
{
break;
}
else
{
bs.write(read);
}
}
String content = new String(bs.toByteArray(), "UTF-8");
fin.close();
bs.close();
return content;
}
}
Java创建文件并向文件写入内容:I/0流简单操作
最新推荐文章于 2024-05-28 09:25:11 发布