public class Main { public static byte[] getFileDataAsBytes(File f) { byte[] data = new byte[(int)f.length()]; try(InputStream is =new FileInputStream(f)) { int n; while((n=is.read(data))!=-1) { System.out.println("read"+n+"bytes"); }
}catch(IOException e) { e.printStackTrace(); } return data; } static void printFiles(File[] files) { System.out.println("=========="); if (files != null) { for (File f : files) { System.out.println(f); } } System.out.println("=========="); }
public static void main(String[] args) throws Exception{ //File对象 File f = new File(".."); System.out.println(f.getPath()); //构造方法传入路径 System.out.println(f.getAbsolutePath()); //返回绝对路径 System.out.println(f.getCanonicalPath());//返回规范绝对路径 System.out.println(File.separator); //返回当前平台系统路径分隔符
// File f1 = new File("C:\\Windows"); // File f2 = new File("C:\\Windows\\notepad.exe"); // File f3 = new File("C:\\Windows\\nothing"); // System.out.println(f1.isFile()); //false 文件 // System.out.println(f1.isDirectory()); //true 目录 // System.out.println(f2.isFile()); //true // System.out.println(f2.isDirectory()); //false // System.out.println(f3.isFile()); //false // System.out.println(f3.isDirectory()); //false
/**InputStream*/ //字节读文件 // 创建一个FileInputStream对象: File file2 = new File("test/readme.txt"); file2.createNewFile(); try (InputStream input = new FileInputStream("test/readme.txt")) { int n; while ((n = input.read()) != -1) { System.out.println(n); } } // 编译器在此自动为我们写入finally并调用close()
//缓冲读文件 try (InputStream input = new FileInputStream("test/readme.txt")) { // 定义1000个字节大小的缓冲区: byte[] buffer = new byte[1000]; int n; while ((n = input.read(buffer)) != -1) { // 读取到缓冲区 System.out.println("read " + n + " bytes."); } } //模拟InputStream String s; byte[] data = { 72, 101, 108, 108, 111, 33 }; try (InputStream input = new ByteArrayInputStream(data)) { int n; StringBuilder sb = new StringBuilder(); while ((n = input.read()) != -1) { sb.append((char) n); System.out.println((char)n); } s = sb.toString(); } System.out.println(s);
/**OutputStream*/ //一次写入一个字节 OutputStream output = new FileOutputStream("test/readme.txt"); output.write(72); // H output.write(101); // e output.write(108); // l output.write(108); // l output.write(111); // o output.close();