java接收文件传入磁盘_【java】读写磁盘文件

一、读txt文件

public static String readFile(File file, String charset){

//设置默认编码

if(charset == null){

charset = "UTF-8";

}

if(file.isFile() && file.exists()){

try {

FileInputStream fileInputStream = new FileInputStream(file);

InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charset);

BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

StringBuffer sb = new StringBuffer();

String text = null;

while((text = bufferedReader.readLine()) != null){

sb.append(text);

}

return sb.toString();

} catch (Exception e) {

// TODO: handle exception

}

}

return null;

}

二、写txt文件

/**

* 以FileWriter方式写入txt文件。

* @param File file:要写入的文件

* @param String content: 要写入的内容

* @param String charset:要写入内容的编码方式

*/

public static void writeToFile1(){

try {

String content = "测试使用字符串";

File file = new File("./File/test1.txt");

if(file.exists()){

FileWriter fw = new FileWriter(file,false);

BufferedWriter bw = new BufferedWriter(fw);

bw.write(content);

bw.close(); fw.close();

System.out.println("test1 done!");

}

} catch (Exception e) {

// TODO: handle exception

}

}

三、文件不存在时候,主动创建文件

public static void writeToFile2(){

try {

String content = "测试使用字符串";

File file = new File("./File/test2.txt");

//文件不存在时候,主动穿件文件。

if(!file.exists()){

file.createNewFile();

}

FileWriter fw = new FileWriter(file,false);

BufferedWriter bw = new BufferedWriter(fw);

bw.write(content);

bw.close(); fw.close();

System.out.println("test2 done!");

} catch (Exception e) {

// TODO: handle exception

}

}

四、使用FileOutputStream来写入txt文件

public static void writeToFile3(){

String content = "测试使用字符串";

FileOutputStream fileOutputStream = null;

File file = new File("./File/test3.txt");

try {

if(file.exists()){

file.createNewFile();

}

fileOutputStream = new FileOutputStream(file);

fileOutputStream.write(content.getBytes());

fileOutputStream.flush();

fileOutputStream.close();

} catch (Exception e) {

// TODO: handle exception

}

System.out.println("test3 done");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值