做个笔记,针对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 ;
}
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;
}
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;
}
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;
}