日志文章

2019-12-23 aflfte2011

IO读取文件内容

package com.aflfte.IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * IO第一个程序 标准写法
 * 流程:
 * 1、创建源
 * 2、选择流
 * 3、操作
 * 4、头释放资源
 * @author jinhao
 *
 */
public class test02 {
public static void main(String[] args) {
//1、创建源
File src = new File("src/abc.txt");
//2、选择流
InputStream is=null;
try {
is=new FileInputStream(src);
//3、操作
int temp;
while((temp=is.read())!=-1) {
System.out.println((char)temp);
}
//4、释放资源
//is.close();

} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
try {
if(is!=null) {
is.close();
}

} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}



package com.aflfte.IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * IO分段读取
 * 流程:
 * 1、创建源
 * 2、选择流
 * 3、操作
 * 4、头释放资源
 * @author jinhao
 *
 */
public class test04 {
public static void main(String[] args) {
//1、创建源
File src = new File("src/abc.txt");
//2、选择流
InputStream is=null;
try {
is=new FileInputStream(src);
//3、操作
byte[] flush=new byte[1024*10];//建立缓冲容器
int len=-1;
while((len=is.read(flush))!=-1) {
String str=new String(flush,0,len);//读取内容
System.out.println(str);
}

/*int temp;
while((temp=is.read())!=-1) {
System.out.println((char)temp);
}*/
//4、释放资源
//is.close();

} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
try {
if(is!=null) {
is.close();
}

} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}


« 利用IO流实现文件的拷贝 | 利用递归统计文件夹大小»