import java.io.File;// I/O input 输入 output 输出
File file = new File("d:/123.txt");//指向这个文件(文件路径)
System.out.println(file.getName());//名字
System.out.println(file.getPath());//相对路径
System.out.println(file.getAbsolutePath());//绝对路径
System.out.println(file.getParent());//上级路径
System.out.println(file.length());//字节长度
System.out.println(file.exists());//判断文件是否存在
System.out.println(file.isFile());//是不是文件
System.out.println(file.isDirectory());//是不是文件夹
try {
file.createNewFile();//创建一个同名空白文件
} catch (Exception e) {
// TODO: handle exception
}
file.delete()//删除
读文件是指把文件的数据读取到内存
InputStream is = new FileInputStream(file);
System.out.println((char)is.read());//读取第一个字
写文件是指把内存的数据写入文件
读数据用输入流
File file = new File("d:/123.txt");
InputStream is = null;
try {
is = new FileInputStream(file);
byte [] bs = new byte[5];
int length = is.read(bs);
while (length != -1) {//避免一直循环
for (byte b : bs) {//读出的数据放在bs数组中了
System.out.print((char)b);//读取第一个字
}
length = is.read(bs);
}
} catch (Exception e) {
// TODO: handle exception
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
写数据用输出流
try {
os.write("123456".getBytes(),3,2);//从下标为三开始添加 ,添加几个
os.write("123456".getBytes(),0,"123456".length());
字符流:
public class Test_10 {
public static void main(String[] args) {
Writer writer = null;
try {
writer = new FileWriter(new File("d:/123.txt"));
writer.write(97);
writer.flush();//刷新
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二进制读文件: