package lib;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Test {
// 定义文件路径
File f = new File("F:\\test.txt");
//字符流写入的方法
public String writeInFile() throws IOException{
String str = "";
String count = "";
try {
// 使用字符流对文件进行读取
BufferedReader bf = new BufferedReader(new FileReader(f));
while (true) {
//读取每一行数据并将其赋值给str
if ((count = bf.readLine()) != null) {
str += count;
} else {
break;
}
}
// 关闭流
bf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return str;
}
//字符流读取的方法
public void getReader(){
try {
//其中true表示在原本文件内容的尾部添加,若不写则表示清空文件后再添加内容
PrintWriter pw=new PrintWriter(new FileWriter(f,true));
pw.write("测试输入字符串到文件中2");
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Test test=new Test();
//将字符串输入到文件中
test.getReader();
//读取相对应的字符串
String str=test.writeInFile();
//将文件中内容在控制台输出
System.out.println("文件内容为:"+str);
}
}
package com.file.test2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestFile2 {
//使用字节流读取并写入文件,将一个文件复制到另一个文件中
public static void main(String[] args) throws IOException {
//要复制的源文件
File f=new File("D:\\test.txt");
//目标文件
File f2=new File("D:\\test2.txt");
//定义一个byte类型的数组,用于存储读取到的内容
byte [] b=new byte[1024];
int length;
try {
//定义读取的流
FileInputStream in=new FileInputStream(f);
//定义输出到文件的流
FileOutputStream out=new FileOutputStream(f2);
//将文件内容输出到另一个文件中
while((length=in.read(b))!=-1){
out.write(b, 0, length);
}
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有