File方法

  1. public class test {
  2. public static void main(String[] args) {
  3. File f = new File("D:\\abc");
  4. f.isDirectory(); //测试此路径是否为路径
  5. f.isFile(); //测试此路径是否为文件
  6. f.exists(); //测试此路径是否存在
  7. f.getAbsolutePath(); //返回此路径的绝对路径字符串
  8. f.getPath(); //将此路径名转换为路径名字符串
  9. f.getName(); //返回此路径名表示的文件或目录名称
  10. f.list(); //返回此路径名中文件和目录名称的字符串数组
  11. f.listFiles(); //返回此路径名中文件和目录的File对象数组
  12. f.delete(); //删除此路径表示的文件或路径
  13. }
  14. }

字节写入

  1. public class test {
  2. public static void main(String[] args) throws IOException {
  3. FileOutputStream f = new FileOutputStream("D:\\abc\\test.txt",true);
  4. f.write("hello".getBytes());
  5. f.close();
  6. }
  7. }
  8. /*
  9. FileOutputStream对象第二个参数为true时,表示为追加模式,否则为覆盖
  10. */

字节读取

  1. public class test {
  2. public static void main(String[] args) throws IOException {
  3. FileInputStream f = new FileInputStream("D:\\abc\\adw.txt");
  4. int by = 1;
  5. while (by != -1){ //当后面没有内容时返回-1
  6. by = f.read();
  7. System.out.print((char) by);
  8. }
  9. }
  10. }

字节缓冲流

  1. public class test {
  2. public static void main(String[] args) throws IOException {
  3. BufferedInputStream bi = new BufferedInputStream(new FileInputStream("D:\\abc\\ci.txt"));
  4. int by;
  5. while ((by = bi.read()) != -1){
  6. System.out.print((char)by);
  7. }
  8. }
  9. }
  10. public class test {
  11. public static void main(String[] args) throws IOException {
  12. BufferedOutputStream bi = new BufferedOutputStream(new FileOutputStream("D:\\abc\\ci.txt"));
  13. bi.write("abc".getBytes());
  14. }
  15. }
  16. //字符串缓冲流会首先将读写的数据存入定义好的字节流数组,然后将字节数组的数据一次性的读写到文件中

字符读取

  1. public class test {
  2. public static void main(String[] args) throws IOException {
  3. FileInputStream f = new FileInputStream("D:\\abc\\adw.txt");
  4. InputStreamReader f1 = new InputStreamReader(f,"utf8"); //设置编码集为utf-8
  5. int by = 1;
  6. while (by != -1){ //当后面没有内容时返回-1
  7. by = f1.read();
  8. System.out.print((char) by);
  9. }
  10. }
  11. }

字符写入

  1. public class test {
  2. public static void main(String[] args) throws IOException {
  3. FileOutputStream f = new FileOutputStream("D:\\abc\\test.txt",true);
  4. OutputStreamWriter f3 = new OutputStreamWriter(f,"utf8"); //设置编码集为utf8
  5. f3.write("你好!");
  6. f3.close();
  7. }
  8. }

字符缓冲流

  1. public class test {
  2. public static void main(String[] args) throws IOException {
  3. FileWriter f = new FileWriter("D:\\abc\\test1.txt");
  4. BufferedWriter f1 = new BufferedWriter(f);
  5. f1.write("你好!");
  6. f1.close();
  7. }
  8. }
  9. //f1.readLine()方法可以读取一行数据
  10. public class test {
  11. public static void main(String[] args) throws IOException {
  12. FileReader f = new FileReader("D:\\abc\\test1.txt");
  13. BufferedReader f1 = new BufferedReader(f);
  14. int ch;
  15. while ((ch = f1.read())!=-1){
  16. System.out.print((char) ch);
  17. }
  18. }
  19. }
  20. //f1.newLine()可以写入一行数据