自己总结的Java实现文件的读写操作
系统
1928 0
做个笔记,针对java 的file的操作
1.根据文件名及字符串,写文件
public
static
boolean
writeJiang(String content,String path,String name)
...
{
try
...
{
File file
=
new
File(path);
System.out.println(
"
文件的路径是:
"
+
file
+
"
/
"
+
name);
BufferedWriter fileout
=
new
BufferedWriter(
new
FileWriter(file
+
"
/
"
+
name,
true
));
fileout.write(content);
fileout.write(
"
"
);
fileout.flush();
fileout.close();
}
catch
(Exception e)
...
{
e.printStackTrace();
}
System.out.println(
"
写文件完毕
"
);
return
true
;
}
2.读文件,返回字符串
public
static
String readTxt(String path)
...
{
String array
=
""
;
try
...
{
//
读取文本文件
File file
=
new
File(path);
FileInputStream rdf
=
new
FileInputStream(file);
byte
[] s
=
new
byte
[rdf.available()];
int
b
=
rdf.available();
while
((b
=
rdf.read(s,
0
, b))
!=-
1
)
...
{
String content
=
new
String(s,
0
,b);
array
=
array
+
content;
}
rdf.close();
}
catch
(Exception e)
...
{
e.printStackTrace();
}
return
array;
}
3.删除文件中某一行.ID是行号,path+name=File
public
static
int
deleteTxt(String path,String name,
int
id)
...
{
int
result
=
0
;
String content
=
""
;
try
...
{
//
读取文件
content
=
readTxt(path
+
"
/
"
+
name);
System.out.println(path
+
"
/
"
+
name);
System.out.println(
"
未删除记录之前得是:
"
+
content);
//
删除某一行
String[] a
=
content.split(
"
"
);
StringBuffer d
=
new
StringBuffer();
for
(
int
j
=
0
; j
<
a.length; j
++
)
...
{
if
(j
!=
id)
d.append(a[j]).append(
"
"
);
}
System.out.println(
"
删除记录之后的为:
"
+
d.toString());
//
将修改后的写入文件
writeNewTxt(d.toString(),path,name);
result
=
1
;
}
catch
(Exception e)
...
{
e.printStackTrace();
}
return
result;
}
自己总结的Java实现文件的读写操作
更多文章、技术交流、商务合作、联系博主
微信扫码或搜索:z360901061
微信扫一扫加我为好友
QQ号联系: 360901061
您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。
【本文对您有帮助就好】元