1.String IOUtils.toString(InputStream input),传入输入流对象,返回字符串,有多重重载,可按需要传参
用例:
@Test
public void showInfoByIOUtils() throws IOException {
URL url = new URL("https://www.baidu.com");
InputStream in = url.openStream();
System.out.println(in);
try {
System.out.println(IOUtils.toString(in));
} catch (IOException e) {
e.printStackTrace();
}
}
2.利用String
FileUtils.readFileToString(File file, String encoding)及
FileUtils.writeStringToFile(File file, String data, String encoding)读写文件:
用例:
@Test
public void editFile() throws IOException {
String fileName = "d://11.txt";
File file = new File(fileName);
String fileContent = "";
try {
fileContent = FileUtils.readFileToString(file, "utf8");
} catch (IOException e) {
e.printStackTrace();
}
fileContent += "Helloworld,我也是";
try {
FileUtils.writeStringToFile(file, fileContent, "utf8");
} catch (IOException e) {
e.printStackTrace();
}
}
3.利用
FileUtils.copyFile(File srcFile, File destFile)复制文件:
用例:
@Test
public void copyFile() throws IOException {
try {
File src = new File("d:\\11.txt");
File dest = new File("e://11.txt");
FileUtils.copyFile(src, dest);// 清空目的文件,然后再粘贴内容
} catch (IOException e) {
e.printStackTrace();
}
}
4.利用
IOUtils.toByteArray(InputStream input)及
FileUtils.writeByteArrayToFile(File file, byte[] data)下载文 件到本地:
用例:
@Test
public void download() throws IOException {
try {
InputStream in = new URL("http://www.baidu.com/img/baidu_logo.gif").openStream();
byte[] gif = IOUtils.toByteArray(in);
FileUtils.writeByteArrayToFile(new File("e:/test.gif"), gif);// 清空目的文件,然后再粘贴内容
} catch (IOException e) {
e.printStackTrace();
}
}
5.利用
FileUtils.copyFileToDirectory(File srcFile, File destDir)复制文件到指定目录:
用例:
@Test
public void copy2dir() throws IOException {
try {
File srcfile = new File("d:\\11.txt");
File destDir = new File("E:\\photoshop cs6");
FileUtils.copyFileToDirectory(srcfile, destDir);// 复制文件到指定目录
} catch (IOException e) {
e.printStackTrace();
}
}
6.利用
FileUtils.copyURLToFile(URL source, File destination)复制url对象到指定文件,相当于网页另存为:
用例:
@Test
public void copyUrl2File() throws Exception {
URL url = new URL("http://www.163.com");
File file = new File("E:\\163.html");
FileUtils.copyURLToFile(url, file);
}
7.利用
FileUtils.cleanDirectory(File directory)清空目录,利用
FileUtils.deleteDirectory(File directory)删除目录:
用例:
@Test
public void cleanOrDeletedeleteDirectory() throws IOException {
try {
File dir = new File("e:\\test");
FileUtils.cleanDirectory(dir);// 清空目录下的文件
FileUtils.deleteDirectory(dir);// 删除目录和目录下的文件
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
}