Java IO 之文件读写简单实例

1.文件读
public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}
2. 文件写
public class AppendToFile {
/**
* A方法追加文件:使用RandomAccessFile
*/
public static void appendMethodA(String fileName, String content) {
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
//将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* B方法追加文件:使用FileWriter
*/
public static void appendMethodB(String fileName, String content) {
try {
//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
String content = "new append!";
//按方法A追加文件
AppendToFile.appendMethodA(fileName, content);
AppendToFile.appendMethodA(fileName, "append end. \n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
//按方法B追加文件
AppendToFile.appendMethodB(fileName, content);
AppendToFile.appendMethodB(fileName, "append end. \n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关文章:
个人摄影网站制作流程,摄影爱好者都去什么网站?
如何在企业微信快速生成手机电脑官网?
最好的网站制作公司,网购哪个网站口碑最好,推荐几个?谢谢?
,在苏州找工作,上哪个网站比较好?
重庆市网站制作公司,重庆招聘网站哪个好?
如何在IIS服务器上快速部署高效网站?
专业制作网站的公司哪家好,建立一个公司网站的费用.有哪些部分,分别要多少钱?
网站制作多少钱一个,建一个论坛网站大约需要多少钱?
C#怎么使用委托和事件 C# delegate与event编程方法
行程制作网站有哪些,第三方机票电子行程单怎么开?
建站之星免费模板:自助建站系统与智能响应式一键生成
如何登录建站主机?访问步骤全解析
*服务器网站为何频现安全漏洞?
武汉网站制作费用多少,在武汉武昌,建面100平方左右的房子,想装暖气片,费用大概是多少啊?
香港服务器网站推广:SEO优化与外贸独立站搭建策略
如何基于云服务器快速搭建个人网站?
如何在建站主机中优化服务器配置?
建站之星后台密码如何安全设置与找回?
如何在景安服务器上快速搭建个人网站?
婚礼视频制作网站,学习*后期制作的网站有哪些?
制作证书网站有哪些,全国城建培训中心证书查询官网?
如何在阿里云虚拟主机上快速搭建个人网站?
如何选择适配移动端的WAP自助建站平台?
建站主机选择指南:服务器配置与SEO优化实战技巧
微信推文制作网站有哪些,怎么做微信推文,急?
建站之星伪静态规则如何设置?
宝塔面板创建网站无法访问?如何快速排查修复?
如何通过.red域名打造高辨识度品牌网站?
高端建站如何打造兼具美学与转化的品牌官网?
电脑免费海报制作网站推荐,招聘海报哪个网站多?
C#怎么创建控制台应用 C# Console App项目创建方法
建站主机系统SEO优化与智能配置核心关键词操作指南
网站建设设计制作营销公司南阳,如何策划设计和建设网站?
佛山企业网站制作公司有哪些,沟通100网上服务官网?
如何在万网开始建站?分步指南解析
如何通过免费商城建站系统源码自定义网站主题与功能?
怎么用手机制作网站链接,dw怎么把手机适应页面变成网页?
电视网站制作tvbox接口,云海电视怎样自定义添加电视源?
,石家庄四十八中学官网?
如何在Golang中指定模块版本_使用go.mod控制版本号
上海制作企业网站有哪些,上海有哪些网站可以让企业免费发布招聘信息?
如何快速上传建站程序避免常见错误?
如何批量查询域名的建站时间记录?
高端企业智能建站程序:SEO优化与响应式模板定制开发
建站之星如何实现PC+手机+微信网站五合一建站?
大连企业网站制作公司,大连2025企业社保缴费网上缴费流程?
香港服务器WordPress建站指南:SEO优化与高效部署策略
独立制作一个网站多少钱,建立网站需要花多少钱?
如何在云指建站中生成FTP站点?
实现点击下箭头变上箭头来回切换的两种方法【推荐】
*请认真填写需求信息,我们会在24小时内与您取得联系。