初学:读写文本文件....

xkent77 2003-10-15 05:19:15
这样写,出错...请问大家是如何用JAVA读写文本文件的?

读文件:
File file_tem = new File (filepath);
if(file_tem.exists())
{
FileReader fr=new FileReader(filepath);
String out_temp;
if(fr.read(out_temp)==1)
{
System.out.println("The content of the file:");
System.out.println(out_temp);
}
else
{
System.out.println("Error");
}
fr.close();
}
return true;
}

写文件:
File file_tem = new File (filepath);
if(file_tem.exists())
{
FileWriter fw=new FileWriter(filepath);
String out_temp="写入文件的内容";
fw.write(out_temp);
fr.close();
}
return true;
}

请教......TKS...
...全文
33 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xkent77 2003-10-20
  • 打赏
  • 举报
回复
FileReader.read()不能将一个文件的内容读出至一个字符串吗?

FileWriter.write()不能将一个字符串直接写入到文件中吗?

要是一个个BYTE写,不是很方便吧..

我看书说:文本文件读写用FileReader/FileWriter....
BYTE文件读写用InputStream/OutputStream.....

对吗??

(初学JAVA,找不到北了)
fuzhan820 2003-10-17
  • 打赏
  • 举报
回复
学习
qixin_lover 2003-10-17
  • 打赏
  • 举报
回复
//package fileutilities;

import java.io.*;
import java.lang.*;
import java.util.*;
import java.sql.*;
//import dbutilities.*;

/*
对文件进行操作
FileReader 每次读取的是一个字符charactor,FileInputStram 每次读取的是一个字节byte
FileReader.read()返回一个int,其取值范围是0 到65535,通常来说是两个字节的;FileWriter.write(int c)
向文件写入一个int,通常来说也是两个字节的,如果某个字符的高位字节为空,那么其高位字节将被舍弃;
FileOutputStream.write(int b)虽然接受一个int作为参数,实际上只向文件写入一个字节,如果传递过来
的参数是一个双字节的汉字,其高位字节将被舍弃,造成文件内容错误。
建议:永远只使用InputStream/OutputStream进行IO操作。

*/
public class fileoperation {

File currentfile;
File currentfile2;
FileReader infile;
FileWriter outfile;
String path=null;

public void deletefile(String delfile) //删除文件,参数是包含绝对路径的文件名
{
try {
//this.path = dir;
currentfile = new File(delfile);
currentfile.delete();
}
catch(Exception ex) { System.out.print(ex); }

}

public void renamefile(String filepath,String sfile,String dfile)//将文件名为sfile的文件更名为dfile
{
try {
this.path = filepath;
currentfile = new File(path+sfile);
currentfile2 = new File(path+dfile);
currentfile.renameTo(currentfile2);
}
catch(Exception ex) { System.out.print(ex); }
}

public void copyfile(String filepath,String sfile,String dfile)//将文件名为sfile的文件进行拷贝,目标文件为dfile
{
try {
this.path = filepath;
currentfile = new File(path+sfile);
currentfile2 = new File(path+dfile);

infile = new FileReader(currentfile);
outfile = new FileWriter(currentfile2);

int c;
while((c = infile.read()) != -1)
{
outfile.write(c);
}

infile.close();
outfile.close();

}
catch(Exception ex){ System.out.print(ex); }
}

public static void main(String args[])
{
fileoperation fileop = new fileoperation();
String filepath="D:/fxbg/email/newmail/upload/";
System.out.println("File Name:");
String soufile="x1.txt";
String desfile="x2.txt";
fileop.copyfile(filepath,soufile,desfile);
}

}
xkent77 2003-10-16
  • 打赏
  • 举报
回复
有人教我吗?

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧