转java io读写大全

本文详细介绍Java中文件的各种操作方法,包括读取文件的不同方式(按字节、字符、行及随机读取),如何将内容追加到文件末尾,以及创建、删除文件和文件夹、复制和移动文件等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自网址 http://www.open-open.com/lib/view/open1356607724791.html
一、多种方式读文件内容。

1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容
4、随机读取文件内容

001
import java.io.BufferedReader;
002
import java.io.File;
003
import java.io.FileInputStream;
004
import java.io.FileReader;
005
import java.io.IOException;
006
import java.io.InputStream;
007
import java.io.InputStreamReader;
008
import java.io.RandomAccessFile;
009
import java.io.Reader;
010
public class ReadFromFile {
011
/**
012
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
013
* @param fileName 文件的名
014
*/
015
public static void readFileByBytes(String fileName){
016
File file = new File(fileName);
017
InputStream in = null;
018
try {
019
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
020
// 一次读一个字节
021
in = new FileInputStream(file);
022
int tempbyte;
023
while((tempbyte=in.read()) != -1){
024
System.out.write(tempbyte);
025
}
026
in.close();
027
} catch (IOException e) {
028
e.printStackTrace();
029
return;
030
}
031
try {
032
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
033
//一次读多个字节
034
byte[] tempbytes = new byte[100];
035
int byteread = 0;
036
in = new FileInputStream(fileName);
037
ReadFromFile.showAvailableBytes(in);
038
//读入多个字节到字节数组中,byteread为一次读入的字节数
039
while ((byteread = in.read(tempbytes)) != -1){
040
System.out.write(tempbytes, 0, byteread);
041
}
042
} catch (Exception e1) {
043
e1.printStackTrace();
044
} finally {
045
if (in != null){
046
try {
047
in.close();
048
} catch (IOException e1) {
049
}
050
}
051
}
052
}
053
/**
054
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
055
* @param fileName 文件名
056
*/
057
public static void readFileByChars(String fileName){
058
File file = new File(fileName);
059
Reader reader = null;
060
try {
061
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
062
// 一次读一个字符
063
reader = new InputStreamReader(new FileInputStream(file));
064
int tempchar;
065
while ((tempchar = reader.read()) != -1){
066
//对于windows下,/r/n这两个字符在一起时,表示一个换行。
067
//但如果这两个字符分开显示时,会换两次行。
068
//因此,屏蔽掉/r,或者屏蔽/n。否则,将会多出很多空行。
069
if (((char)tempchar) != '/r'){
070
System.out.print((char)tempchar);
071
}
072
}
073
reader.close();
074
} catch (Exception e) {
075
e.printStackTrace();
076
}
077
try {
078
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
079
//一次读多个字符
080
char[] tempchars = new char[30];
081
int charread = 0;
082
reader = new InputStreamReader(new FileInputStream(fileName));
083
//读入多个字符到字符数组中,charread为一次读取字符数
084
while ((charread = reader.read(tempchars))!=-1){
085
//同样屏蔽掉/r不显示
086
if ((charread == tempchars.length)&&(tempchars[tempchars.length-1] != '/r')){
087
System.out.print(tempchars);
088
}else{
089
for (int i=0; i<charread; i++){
090
if(tempchars[i] == '/r'){
091
continue;
092
}else{
093
System.out.print(tempchars[i]);
094
}
095
}
096
}
097
}
098

099
} catch (Exception e1) {
100
e1.printStackTrace();
101
}finally {
102
if (reader != null){
103
try {
104
reader.close();
105
} catch (IOException e1) {
106
}
107
}
108
}
109
}
110
/**
111
* 以行为单位读取文件,常用于读面向行的格式化文件
112
* @param fileName 文件名
113
*/
114
public static void readFileByLines(String fileName){
115
File file = new File(fileName);
116
BufferedReader reader = null;
117
try {
118
System.out.println("以行为单位读取文件内容,一次读一整行:");
119
reader = new BufferedReader(new FileReader(file));
120
String tempString = null;
121
int line = 1;
122
//一次读入一行,直到读入null为文件结束
123
while ((tempString = reader.readLine()) != null){
124
//显示行号
125
System.out.println("line " + line + ": " + tempString);
126
line++;
127
}
128
reader.close();
129
} catch (IOException e) {
130
e.printStackTrace();
131
} finally {
132
if (reader != null){
133
try {
134
reader.close();
135
} catch (IOException e1) {
136
}
137
}
138
}
139
}
140
/**
141
* 随机读取文件内容
142
* @param fileName 文件名
143
*/
144
public static void readFileByRandomAccess(String fileName){
145
RandomAccessFile randomFile = null;
146
try {
147
System.out.println("随机读取一段文件内容:");
148
// 打开一个随机访问文件流,按只读方式
149
randomFile = new RandomAccessFile(fileName, "r");
150
// 文件长度,字节数
151
long fileLength = randomFile.length();
152
// 读文件的起始位置
153
int beginIndex = (fileLength > 4) ? 4 : 0;
154
//将读文件的开始位置移到beginIndex位置。
155
randomFile.seek(beginIndex);
156
byte[] bytes = new byte[10];
157
int byteread = 0;
158
//一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
159
//将一次读取的字节数赋给byteread
160
while ((byteread = randomFile.read(bytes)) != -1){
161
System.out.write(bytes, 0, byteread);
162
}
163
} catch (IOException e){
164
e.printStackTrace();
165
} finally {
166
if (randomFile != null){
167
try {
168
randomFile.close();
169
} catch (IOException e1) {
170
}
171
}
172
}
173
}
174
/**
175
* 显示输入流中还剩的字节数
176
* @param in
177
*/
178
private static void showAvailableBytes(InputStream in){
179
try {
180
System.out.println("当前字节输入流中的字节数为:" + in.available());
181
} catch (IOException e) {
182
e.printStackTrace();
183
}
184
}
185

186
public static void main(String[] args) {
187
String fileName = "C:/temp/newTemp.txt";
188
ReadFromFile.readFileByBytes(fileName);
189
ReadFromFile.readFileByChars(fileName);
190
ReadFromFile.readFileByLines(fileName);
191
ReadFromFile.readFileByRandomAccess(fileName);
192
}
193
}


二、将内容追加到文件尾部

001
import java.io.FileWriter;
002
import java.io.IOException;
003
import java.io.RandomAccessFile;
004

005
/**
006
* 将内容追加到文件尾部
007
*/
008
public class AppendToFile {
009

010
/**
011
* A方法追加文件:使用RandomAccessFile
012
* @param fileName 文件名
013
* @param content 追加的内容
014
*/
015
public static void appendMethodA(String fileName, String content){
016
try {
017
// 打开一个随机访问文件流,按读写方式
018
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
019
// 文件长度,字节数
020
long fileLength = randomFile.length();
021
//将写文件指针移到文件尾。
022
randomFile.seek(fileLength);
023
randomFile.writeBytes(content);
024
randomFile.close();
025
} catch (IOException e){
026
e.printStackTrace();
027
}
028
}
029
/**
030
* B方法追加文件:使用FileWriter
031
* @param fileName
032
* @param content
033
*/
034
public static void appendMethodB(String fileName, String content){
035
try {
036
//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
037
FileWriter writer = new FileWriter(fileName, true);
038
writer.write(content);
039
writer.close();
040
} catch (IOException e) {
041
e.printStackTrace();
042
}
043
}
044

045
public static void main(String[] args) {
046
String fileName = "C:/temp/newTemp.txt";
047
String content = "new append!";
048
//按方法A追加文件
049
AppendToFile.appendMethodA(fileName, content);
050
AppendToFile.appendMethodA(fileName, "append end. /n");
051
//显示文件内容
052
ReadFromFile.readFileByLines(fileName);
053
//按方法B追加文件
054
AppendToFile.appendMethodB(fileName, content);
055
AppendToFile.appendMethodB(fileName, "append end. /n");
056
//显示文件内容
057
ReadFromFile.readFileByLines(fileName);
058
}
059
}
060

061
三文件的各种操作类
062

063
import java.io.*;
064

065
/**
066
* FileOperate.java
067
* 文件的各种操作
068
* @author 杨彩 http://blog.sina.com.cn/m/yangcai
069
* 文件操作 1.0
070
*/
071

072
public class FileOperate
073
{
074

075
public FileOperate()
076
{
077
}
078
/**
079
* 新建目录
080
*/
081
public void newFolder(String folderPath)
082
{
083
try
084
{
085
String filePath = folderPath;
086
filePath = filePath.toString();
087
File myFilePath = new File(filePath);
088
if(!myFilePath.exists())
089
{
090
myFilePath.mkdir();
091
}
092
System.out.println("新建目录操作 成功执行");
093
}
094
catch(Exception e)
095
{
096
System.out.println("新建目录操作出错");
097
e.printStackTrace();
098
}
099
}
100
/**
101
* 新建文件
102
*/
103
public void newFile(String filePathAndName, String fileContent)
104
{
105
try
106
{
107
String filePath = filePathAndName;
108
filePath = filePath.toString();
109
File myFilePath = new File(filePath);
110
if (!myFilePath.exists())
111
{
112
myFilePath.createNewFile();
113
}
114
FileWriter resultFile = new FileWriter(myFilePath);
115
PrintWriter myFile = new PrintWriter(resultFile);
116
String strContent = fileContent;
117
myFile.println(strContent);
118
resultFile.close();
119
System.out.println("新建文件操作 成功执行");
120
}
121
catch (Exception e)
122
{
123
System.out.println("新建目录操作出错");
124
e.printStackTrace();
125
}
126
}
127
/**
128
* 删除文件
129
*/
130
public void delFile(String filePathAndName)
131
{
132
try
133
{
134
String filePath = filePathAndName;
135
filePath = filePath.toString();
136
File myDelFile = new File(filePath);
137
myDelFile.delete();
138
System.out.println("删除文件操作 成功执行");
139
}
140
catch (Exception e)
141
{
142
System.out.println("删除文件操作出错");
143
e.printStackTrace();
144
}
145
}
146
/**
147
* 删除文件夹
148
*/
149
public void delFolder(String folderPath)
150
{
151
try
152
{
153
delAllFile(folderPath); //删除完里面所有内容
154
String filePath = folderPath;
155
filePath = filePath.toString();
156
File myFilePath = new File(filePath);
157
if(myFilePath.delete()) { //删除空文件夹
158
System.out.println("删除文件夹" + folderPath + "操作 成功执行");
159
} else {
160
System.out.println("删除文件夹" + folderPath + "操作 执行失败");
161
}
162
}
163
catch (Exception e)
164
{
165
System.out.println("删除文件夹操作出错");
166
e.printStackTrace();
167
}
168
}
169
/**
170
* 删除文件夹里面的所有文件
171
* @param path String 文件夹路径 如 c:/fqf
172
*/
173
public void delAllFile(String path)
174
{
175
File file = new File(path);
176
if(!file.exists())
177
{
178
return;
179
}
180
if(!file.isDirectory())
181
{
182
return;
183
}
184
String[] tempList = file.list();
185
File temp = null;
186
for (int i = 0; i < tempList.length; i++)
187
{
188
if(path.endsWith(File.separator))
189
{
190
temp = new File(path + tempList[i]);
191
}
192
else
193
{
194
temp = new File(path + File.separator + tempList[i]);
195
}
196
if (temp.isFile())
197
{
198
temp.delete();
199
}
200
if (temp.isDirectory())
201
{
202
//delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
203
delFolder(path+ File.separatorChar + tempList[i]);//再删除空文件夹
204
}
205
}
206
System.out.println("删除文件操作 成功执行");
207
}
208
/**
209
* 复制单个文件
210
* @param oldPath String 原文件路径 如:c:/fqf.txt
211
* @param newPath String 复制后路径 如:f:/fqf.txt
212
*/
213
public void copyFile(String oldPath, String newPath)
214
{
215
try
216
{
217
int bytesum = 0;
218
int byteread = 0;
219
File oldfile = new File(oldPath);
220
if (oldfile.exists())
221
{
222
//文件存在时
223
InputStream inStream = new FileInputStream(oldPath); //读入原文件
224
FileOutputStream fs = new FileOutputStream(newPath);
225
byte[] buffer = new byte[1444];
226
while ( (byteread = inStream.read(buffer)) != -1)
227
{
228
bytesum += byteread; //字节数 文件大小
229
System.out.println(bytesum);
230
fs.write(buffer, 0, byteread);
231
}
232
inStream.close();
233
}
234
System.out.println("删除文件夹操作 成功执行");
235
}
236
catch (Exception e)
237
{
238
System.out.println("复制单个文件操作出错");
239
e.printStackTrace();
240
}
241
}
242
/**
243
* 复制整个文件夹内容
244
* @param oldPath String 原文件路径 如:c:/fqf
245
* @param newPath String 复制后路径 如:f:/fqf/ff
246
*/
247
public void copyFolder(String oldPath, String newPath)
248
{
249
try
250
{
251
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
252
File a=new File(oldPath);
253
String[] file=a.list();
254
File temp=null;
255
for (int i = 0; i < file.length; i++)
256
{
257
if(oldPath.endsWith(File.separator))
258
{
259
temp=new File(oldPath+file[i]);
260
}
261
else
262
{
263
temp=new File(oldPath+File.separator+file[i]);
264
}
265
if(temp.isFile())
266
{
267
FileInputStream input = new FileInputStream(temp);
268
FileOutputStream output = new FileOutputStream(newPath + "/" +
269
(temp.getName()).toString());
270
byte[] b = new byte[1024 * 5];
271
int len;
272
while ( (len = input.read(b)) != -1)
273
{
274
output.write(b, 0, len);
275
}
276
output.flush();
277
output.close();
278
input.close();
279
}
280
if(temp.isDirectory())
281
{
282
//如果是子文件夹
283
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
284
}
285
}
286
System.out.println("复制文件夹操作 成功执行");
287
}
288
catch (Exception e)
289
{
290
System.out.println("复制整个文件夹内容操作出错");
291
e.printStackTrace();
292
}
293
}
294
/**
295
* 移动文件到指定目录
296
* @param oldPath String 如:c:/fqf.txt
297
* @param newPath String 如:d:/fqf.txt
298
*/
299
public void moveFile(String oldPath, String newPath)
300
{
301
copyFile(oldPath, newPath);
302
delFile(oldPath);
303
}
304
/**
305
* 移动文件到指定目录
306
* @param oldPath String 如:c:/fqf.txt
307
* @param newPath String 如:d:/fqf.txt
308
*/
309
public void moveFolder(String oldPath, String newPath)
310
{
311
copyFolder(oldPath, newPath);
312
delFolder(oldPath);
313
}
314
public static void main(String args[])
315
{
316
String aa,bb;
317
boolean exitnow=false;
318
System.out.println("使用此功能请按[1] 功能一:新建目录");
319
System.out.println("使用此功能请按[2] 功能二:新建文件");
320
System.out.println("使用此功能请按[3] 功能三:删除文件");
321
System.out.println("使用此功能请按[4] 功能四:删除文件夹");
322
System.out.println("使用此功能请按[5] 功能五:删除文件夹里面的所有文件");
323
System.out.println("使用此功能请按[6] 功能六:复制文件");
324
System.out.println("使用此功能请按[7] 功能七:复制文件夹的所有内容");
325
System.out.println("使用此功能请按[8] 功能八:移动文件到指定目录");
326
System.out.println("使用此功能请按[9] 功能九:移动文件夹到指定目录");
327
System.out.println("使用此功能请按[10] 退出程序");
328
while(!exitnow)
329
{
330
FileOperate fo=new FileOperate();
331
try
332
{
333
BufferedReader Bin=new BufferedReader(new InputStreamReader(System.in));
334
String a=Bin.readLine();
335
int b=Integer.parseInt(a);
336
switch(b)
337
{
338
case 1:System.out.println("你选择了功能一 请输入目录名");
339
aa=Bin.readLine();
340
fo.newFolder(aa);
341
break;
342
case 2:System.out.println("你选择了功能二 请输入文件名");
343
aa=Bin.readLine();
344
System.out.println("请输入在"+aa+"中的内容");
345
bb=Bin.readLine();
346
fo.newFile(aa,bb);
347
break;
348
case 3:System.out.println("你选择了功能三 请输入文件名");
349
aa=Bin.readLine();
350
fo.delFile(aa);
351
break;
352
case 4:System.out.println("你选择了功能四 请输入文件名");
353
aa=Bin.readLine();
354
fo.delFolder(aa);
355
break;
356
case 5:System.out.println("你选择了功能五 请输入文件名");
357
aa=Bin.readLine();
358
fo.delAllFile(aa);
359
break;
360
case 6:System.out.println("你选择了功能六 请输入文件名");
361
aa=Bin.readLine();
362
System.out.println("请输入目标文件名");
363
bb=Bin.readLine();
364
fo.copyFile(aa,bb);
365
break;
366
case 7:System.out.println("你选择了功能七 请输入源文件名");
367
aa=Bin.readLine();
368
System.out.println("请输入目标文件名");
369
bb=Bin.readLine();
370
fo.copyFolder(aa,bb);
371
break;
372
case 8:System.out.println("你选择了功能八 请输入源文件名");
373
aa=Bin.readLine();
374
System.out.println("请输入目标文件名");
375
bb=Bin.readLine();
376
fo.moveFile(aa,bb);
377
break;
378
case 9:System.out.println("你选择了功能九 请输入源文件名");
379
aa=Bin.readLine();
380
System.out.println("请输入目标文件名");
381
bb=Bin.readLine();
382
fo.moveFolder(aa,bb);
383
break;
384
case 10:exitnow=true;
385
System.out.println("程序结束,请退出");
386
break;
387
default:System.out.println("输入错误.请输入1-10之间的数");
388
}
389
System.out.println("请重新选择功能");
390
}
391
catch(Exception e)
392
{
393
System.out.println("输入错误字符或程序出错");
394
}
395
}
396
}
397
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值