File方法
public class test {
public static void main(String[] args) {
File f = new File("D:\\abc");
f.isDirectory(); //测试此路径是否为路径
f.isFile(); //测试此路径是否为文件
f.exists(); //测试此路径是否存在
f.getAbsolutePath(); //返回此路径的绝对路径字符串
f.getPath(); //将此路径名转换为路径名字符串
f.getName(); //返回此路径名表示的文件或目录名称
f.list(); //返回此路径名中文件和目录名称的字符串数组
f.listFiles(); //返回此路径名中文件和目录的File对象数组
f.delete(); //删除此路径表示的文件或路径
}
}
字节写入
public class test {
public static void main(String[] args) throws IOException {
FileOutputStream f = new FileOutputStream("D:\\abc\\test.txt",true);
f.write("hello".getBytes());
f.close();
}
}
/*
FileOutputStream对象第二个参数为true时,表示为追加模式,否则为覆盖
*/
字节读取
public class test {
public static void main(String[] args) throws IOException {
FileInputStream f = new FileInputStream("D:\\abc\\adw.txt");
int by = 1;
while (by != -1){ //当后面没有内容时返回-1
by = f.read();
System.out.print((char) by);
}
}
}
字节缓冲流
public class test {
public static void main(String[] args) throws IOException {
BufferedInputStream bi = new BufferedInputStream(new FileInputStream("D:\\abc\\ci.txt"));
int by;
while ((by = bi.read()) != -1){
System.out.print((char)by);
}
}
}
public class test {
public static void main(String[] args) throws IOException {
BufferedOutputStream bi = new BufferedOutputStream(new FileOutputStream("D:\\abc\\ci.txt"));
bi.write("abc".getBytes());
}
}
//字符串缓冲流会首先将读写的数据存入定义好的字节流数组,然后将字节数组的数据一次性的读写到文件中
字符读取
public class test {
public static void main(String[] args) throws IOException {
FileInputStream f = new FileInputStream("D:\\abc\\adw.txt");
InputStreamReader f1 = new InputStreamReader(f,"utf8"); //设置编码集为utf-8
int by = 1;
while (by != -1){ //当后面没有内容时返回-1
by = f1.read();
System.out.print((char) by);
}
}
}
字符写入
public class test {
public static void main(String[] args) throws IOException {
FileOutputStream f = new FileOutputStream("D:\\abc\\test.txt",true);
OutputStreamWriter f3 = new OutputStreamWriter(f,"utf8"); //设置编码集为utf8
f3.write("你好!");
f3.close();
}
}
字符缓冲流
public class test {
public static void main(String[] args) throws IOException {
FileWriter f = new FileWriter("D:\\abc\\test1.txt");
BufferedWriter f1 = new BufferedWriter(f);
f1.write("你好!");
f1.close();
}
}
//f1.readLine()方法可以读取一行数据
public class test {
public static void main(String[] args) throws IOException {
FileReader f = new FileReader("D:\\abc\\test1.txt");
BufferedReader f1 = new BufferedReader(f);
int ch;
while ((ch = f1.read())!=-1){
System.out.print((char) ch);
}
}
}
//f1.newLine()可以写入一行数据