main执行步骤
:
1.one()方法之后在生成的文件中加入一些文本,这个方法是对字节流的使用;
2.tow()这个方法是对字符流的使用
代码
import java.nio.charset.StandardCharsets;
public class Iotext {
static File f=new File("D:\\IO练手","one.txt");
static File f2=new File("D:\\IO练手","tow.txt");
static FileOutputStream fileOutputStream;
static FileInputStream fileInputStream;
public static void one(){
if(f.exists()){
System.out.println("文件存在");
f.delete();
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
if(f.createNewFile()){
System.out.println("创建成功");
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fileOutputStream=new FileOutputStream(f);
byte [] a="我爱Java".getBytes();
try {
fileOutputStream.write(a );
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fileInputStream=new FileInputStream(f);
byte[] a= new byte[(int)f.length()];
try {
fileInputStream.read(a);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String aa=new String(a);
System.out.println(aa);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void tow() throws IOException{
if (!f.exists()){
one();
}
if (!f2.exists()){
f2.createNewFile();
}
FileReader fileReader=new FileReader(f);
FileWriter fileWriter=new FileWriter(f2);
//保存读取到的数据
int data;
while ((data=fileReader.read())>-1){
fileWriter.write(data);
}
fileReader.close();
fileWriter.close();
fileInputStream =new FileInputStream(f2);
byte[]f2du=new byte[(int)f2.length()];
fileInputStream.read(f2du);
String sf2du=new String(f2du);
System.out.println("f2的内容"+sf2du);
fileInputStream.close();
}
public static void main(String[] args) {
// one();//fileInputStream和fileOutputStream
try {
tow();//filewrite和fileRead
} catch (IOException e) {
e.printStackTrace();
}
}
}