java最全文件读写操作,换行.删除......

package t;

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

public class TestFile {
public static void main(String[] a) {
// 创建文件
writeFile("E:\\resin", "我想飞.txt");
// 读文件
readFile("E:\\resin\\我想飞.txt");
}

/**
* 读文件
*
* @param path
* @return boolean
*/
public static boolean readFile(String path) {
File file = new File(path);
// 是否存在
if (!file.exists()) {
System.out.println(path + " 文件不存在");
return false;
}
FileInputStream in;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
return false;
}
byte[] b = new byte[150];
try {

while (in.read() != -1) {
in.read(b);
System.out.println(new String(b).toString());
}
// 关闭流
in.close();
} catch (IOException e) {
return false;
}

return true;
}

/**
* 写文件
*
* @param path
* @param fileName
* @return boolean
*/
public static boolean writeFile(String path, String fileName) {
File file = new File(path);
boolean bool = false;
// 是否存在
if (!file.exists())
// 创建文件夹
file.mkdir();
// 判断后缀是否含有\\
if (path.endsWith("\\"))
file = new File(path + fileName);
else
file = new File(path + "\\" + fileName);

// file.deleteOnExit();// 删除已存在滴文件
try {
file.createNewFile();// 创建文件(覆盖原来的文件)
// 创建输入流对象
FileOutputStream out = new FileOutputStream(file);
String s = "我想飞=60\r\n";
byte[] b = s.getBytes();
out.write(b);
s = "age=21\r\n";//换行
b = s.getBytes();
out.write(b);
s = "sex=男\r\n";
b = s.getBytes();
out.write(b);
// 关闭流
out.close();
} catch (Exception e) {
System.out.println("写文件失败");
return false;
}
return true;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值