基础知识点复习——输入输出

本文详细介绍了使用Java进行文件操作的方法,包括如何使用File类来判断文件是否存在、创建新文件等,以及通过InputStream和OutputStream实现文件内容的读写。此外,还展示了如何利用Reader和Writer类进行字符流的读写操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入输出
一、file类
1.常用方法:
file.exists() 判断文件是否存在
file.isFile() 判断是否是文件
file.isDirectory() 判断是否是目录
file.getPath() 得到相对路径
file.getAbsolutePath() 得到绝对路径
file.getName() 得到文件名称
file.delete() 删除指定文件
file.createNewFile() 创建新文件

二、输入输出流
InputStream Reader 输入

package file;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class TestFile {
public static void main(String[] args) {
File file = new File("d:/a.txt");
FileInputStream f = null;
try {
f = new FileInputStream(file);
int a;
while((a=f.read())!=-1){
System.out.print((char)a);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}






OutputStream Writer 输出
package file;


import java.io.*;


public class OutputTest {
public static void main(String[] args) {
File file = new File("D:/b.txt");
FileOutputStream fo = null;
try {
fo = new FileOutputStream(file);
byte[] b = new byte[10];
b[0] = 'a';
b[1] = 'b';
fo.write(b);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}


Reader 读取
package file;


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


import javax.swing.text.AbstractDocument.BranchElement;


public class ReaderTest {
public static void main(String[] args) throws Exception {
FileReader fr = null;
BufferedReader bf = null;
try {
fr = new FileReader("D:/a.txt");//要读取的文件路径
bf = new BufferedReader(fr);//讲文件中的内容放在缓冲区中
String line;//定义一个变量,每次读取一行,存储在这个变量中
while((line=bf.readLine())!=null){//每次读取一行,知道读取没有内容
System.out.println(line);//打印读取的一行数据
}
} catch (Exception e) {
e.printStackTrace();
}finally{//关闭资源
bf.close();
fr.close();
}

}
}


writer
package file;


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;


public class WriterTest {
public static void main(String[] args) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter("D:/c.txt");
bw = new BufferedWriter(fw);

bw.write("我是小黑,但是我就是很黑");
bw.newLine();//换行
bw.write("我是小白,但是我就是不白");

} catch (Exception e) {
e.printStackTrace();
}finally{
try {
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值