使用FileUtils类操作文件读写与拷贝
1.读取内容
package com.commons;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
public class IOTest03 {
public static void main(String[] args) throws IOException {
String msg=FileUtils.readFileToString(new File("E:\\java300集\\javaIO\\src\\com\\commons\\emp.txt"),"GBK");
System.out.println(msg);
byte[] datas = FileUtils.readFileToByteArray(new File("E:\\java300集\\javaIO\\src\\com\\commons\\emp.txt"));
readByte(datas);
List<String> msgs = FileUtils.readLines(new File("E:\\java300集\\javaIO\\src\\com\\commons\\emp.txt"),"GBK");
for (String string : msgs) {
System.out.println(string);
}
LineIterator it =FileUtils.lineIterator(new File("E:\\java300集\\javaIO\\src\\com\\commons\\emp.txt"),"GBK");
while(it.hasNext()) {
System.out.println(it.nextLine());
}
}
public static void readByte(byte[] datas) {
InputStream is = null;
try {
is = new ByteArrayInputStream(datas);
byte[] flush = new byte[5];
int len = -1;
while((len=is.read(flush))!=-1) {
String str = new String(flush,0,len);
System.out.println(str);
}
}
catch(IOException e){
e.printStackTrace();
}finally {
try {
if(null!=is )
is.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.写入内容
package com.commons;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class IOTest04 {
public static void main(String[] args) throws IOException {
FileUtils.write(new File("test.txt"), "学习是一件伟大的事业\r\n","GBK");
FileUtils.writeStringToFile(new File("test.txt"), "学习是一件辛苦的事业\r\n","GBK",true);
FileUtils.writeByteArrayToFile(new File("test.txt"), "学习是一件幸福的事业\r\n".getBytes("GBK"),true);
List<String> datas =new ArrayList<String>();
datas.add("3");
datas.add("2");
datas.add("1");
FileUtils.writeLines(new File("test.txt"), datas,"/",true);
}
}
3.文件拷贝
package com.commons;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class IOTest05 {
public static void main(String[] args) throws IOException {
FileUtils.copyFile(new File("p.jpg"), new File("p-copy.jpg"));
FileUtils.copyFileToDirectory(new File("p.jpg"), new File("lib"));
FileUtils.copyDirectoryToDirectory(new File("lib"), new File("lib2"));
FileUtils.copyDirectory(new File("lib"), new File("lib2"));
String url="https://pic2.zhimg.com/v2-7d01cab20858648cbf62333a7988e6d0_qhd.jpg";
FileUtils.copyURLToFile(new URL(url), new File("marvel.jpg"));
String datas = IOUtils.toString(new URL("http://www.baidu.com"),"utf-8");
System.out.println(datas);
}
}