IOUtils常用方法的使用
/**
* apache.commons.io.IOUtils常用方法的使用
* 對字節流inputStream,outStream,writer,reader字符流的常用方法的使用
* @author ZYY
*
*/
public class TestCommon {
public static void main(String[] args) throws IOException {
testLineIterator();
}
/**
* CloseQuietly可以關閉inputStream,outputStream,reader,writer流
*
* @throws IOException
*/
public static void testCloseQuietly() throws IOException {
String filename = “D:” + File.separator + “data.txt”;
File f = new File(filename);
InputStream in = new FileInputStream(f);
// 讀取內容
byte[] b = new byte[1024];
in.read(b);
System.out.println(new String(b));
OutputStream out = new FileOutputStream(f, true);
String str = “我們是幸運的”;
out.write(str.getBytes());
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
/**
* toString的使用
* @throws IOException
*/
public static void testToString() throws IOException {
String filename = “D:” + File.separator + “data.txt”;
File f = new File(filename);
InputStream in = new FileInputStream(f);
System.out.println(IOUtils.toString(in));
IOUtils.closeQuietly(in);
}
/**
* copy的使用
* copy能拷貝Integer.MAX_VALUE的字節數據,即2^31-1。
* 如果是很大的數據,那么可以選擇用copyLarge方法,適合拷貝較大的數據流,比如2G以上
* @throws IOException
*/
public static void testCopy() throws IOException {
String filename = “D:” + File.separator + “data.txt”;
String filename2=”D:”+File.separator+”data2.txt”;
File f = new File(filename);
File f2=new File(filename2);
InputStream input1=new FileInputStream(f2);
InputStream in = new FileInputStream(f);
System.out.println(“未復制之前:”+IOUtils.toString(input1));
OutputStream out=new FileOutputStream(f2);
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
InputStream input2=new FileInputStream(f2);
System.out.println(“復制之后:”+IOUtils.toString(input2));
IOUtils.closeQuietly(input1);
IOUtils.closeQuietly(input2);
}
/**
* ToByteArray的使用
* @throws IOException
*/
public static void testToByteArray() throws IOException {
String filename=”D:”+File.separator+”data.txt”;
File f=new File(filename);
InputStream in=new FileInputStream(f);
byte[] byteArray = IOUtils.toByteArray(in);
System.out.println(new String(byteArray));
IOUtils.closeQuietly(in);
}
/**
* 測試write
* @throws IOException
*/
public static void testWrite() throws IOException {
String filename=”D:”+File.separator+”data.txt”;
File f=new File(filename);
OutputStream out=new FileOutputStream(f);
IOUtils.write(“我們是幸運的”, out);
IOUtils.closeQuietly(out);
InputStream in=new FileInputStream(f);
System.out.println(IOUtils.toString(in));
IOUtils.closeQuietly(in);
}
/**
* 測試ToInputStream
* @throws IOException
*/
public static void testToInputStream() throws IOException {
}
總結
以上是生活随笔為你收集整理的IOUtils常用方法的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在ASP程序中访问Access数据库
- 下一篇: js在类的方法中访问自己的属性