JAVA 读写

主要有两种方式去进行文件操作,第一种是通过FileReader和FileWriter,这种方式对于小规模的文件读取来说较为合适。代码如下:

public static void writeFile1()

{

String fileName="input.txt";

try {

FileWriter writer=new FileWriter(fileName);

writer.write("Somebody is a boy with poor coding skills");

writer.write("Such a beautiful@@ girl!!!");

writer.close();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}
}

publicstaticvoid readFile1()

{

String fileName="input.txt";

try{

FileReader reader=new FileReader(fileName);

int c=0;

c=reader.read();

while(c!=-1)

{

System.out.println((char)c);

c=reader.read();

}

reader.close();

} catch(Exception e){

e.printStackTrace();

}

}

第二种方式是通过BufferReader和BufferWriter实现,这种实现方式更适合有大规模的文件读取需求。

public static void writeFile2() //针对大量输入

{

String fileName="input2.txt";

try{

BufferedWriter writer=new BufferedWriter(new FileWriter(fileName));

writer.write("A cool boy");

writer.newLine();

writer.write("Such a beautiful@@ girl!!!");

writer.close();

} catch (Exception e){

e.printStackTrace();

}

}



publicstaticvoid readFile2()

{

String fileName="input.txt";

try {

BufferedReader in=new BufferedReader(new FileReader(fileName));

String line=in.readLine();

while(line!=null)

{

System.out.println(line);

line=in.readLine();

}

in.close();

} catch (Exception e) {

// TODO: handle exception

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值