[Java 基础]-- java 读和写txt文件(不写入指定字符)
1、通用复制文件photo.jpg(可以是任意格式的文件)到指定目录(如photoOpy.jpg)下://创建输入流FileInputStream reader=new FileInputStream("F:/photo.jpg");//创建输出流FileOutputStream writer=new FileOutputStream(F:/photoCopy.jpg);//定
1、通用复制文件photo.jpg(可以是任意格式的文件)到指定目录(如photoOpy.jpg)下:
//创建输入流
FileInputStream reader=new FileInputStream("F:/photo.jpg");
//创建输出流
FileOutputStream writer=new FileOutputStream(F:/photoCopy.jpg);
//定义读的字节数组大小
byte b[]=new byte[1024];
int length;
while((length=reader.read(b))!=-1){
//将数据写入文件
writer.write(b,0,length);
}
//关闭读
reader.close();
//关闭写
writer.close();
2、读取txt文件内容
(1)测试用字节流转字符流读取txt文件
@Test
public void testReadTxt() {
String filePath = "D:/qq.log";
List<Object> list = new ArrayList<Object>();
Object textContent = null;
try {
File file = new File(filePath);
if (file.isFile()) {
// 创建输入流,读取字节文件
FileInputStream fs = new FileInputStream(file);
// 创建转换流,将字节流转换成字符流,默认编码格式是GBK
InputStreamReader isr = new InputStreamReader(fs, "UTF-8");
// 创建缓冲流读取
BufferedReader br = new BufferedReader(isr);
// 开始读取数据
while ((textContent = br.readLine()) != null) {
list.add(textContent);
}
} else {
System.out.println("文件不存在!");
}
// 遍历文件内容
for (Object ob : list) {
System.out.println(ob);
}
} catch (Exception e) {
e.printStackTrace();
}
}
(2)使用纯字符流读取txt文件
@Test
public void testResadTxt2()throws Exception{
String path="F:/testFileWriter.txt";
FileReader fr=null;
BufferedReader br=null;
try{
//如果不写new File()而直接写path也可以,但是如果使用path,那么会多一次判断而花费时间!
// fr=new FileReader(path);
fr=new FileReader(new File(path));
br=new BufferedReader(fr);
while(br.readLine()!=null){
System.out.println(br.readLine());
}
}catch(Exception e){
e.printStackTrace();
}finally{
br.close();
fr.close();
}
}
3、写入txt文件
@Test
public void writerTxt(){
String txtPath="D:/20151104qwer.log";
try{
FileWriter fw=new FileWriter(new File(txtPath),true);
BufferedWriter rw=new BufferedWriter(fw);
rw.write("hello world"+"\r\n");
rw.close();
fw.close();
}catch(Exception e){
e.printStackTrace();
}
}

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)