Java File IO
~主要介绍四个类 InputStream OutputStream FileReader FileWriter~
InputStream (字节流读取File)
public static void main(String[] args) throws IOException {String filePath = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileInputStream fileInputStream = new FileInputStream(filePath);int read;//如果读到的是-1就说明没有了 读完了while ((read = fileInputStream.read())!= -1){System.out.print((char)read);}}
OutputStream(字节流写入File)
public static void main(String[] args) throws IOException {String filePath = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileOutputStream fileOutputStream = new FileOutputStream(filePath,true);String outPut = "sadfasd";fileOutputStream.write(outPut.getBytes());fileOutputStream.close();}
FileReader(字符流读取File)
public static void main(String[] args) throws IOException {String filePath = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileReader fileReader = new FileReader(filePath);int readLean = 0; //读取的字符串长度char[] charBuf = new char[8];while ((readLean = fileReader.read(charBuf)) != -1){System.out.print(new String(charBuf, 0, readLean));}}
注:这个方法可以读取汉字
public static void main(String[] args) throws IOException {String filePath = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileReader fileReader = new FileReader(filePath);int read = 0;while ((read = fileReader.read()) != -1){System.out.print((char)read);}}
注:这个方法效率低
FileWriter(字符流写入File)
public static void main(String[] args) throws IOException {String filePtah = "D:\\Javaideaporject\\JavaBaseSolid8\\File\\test.txt";FileWriter fileWriter = new FileWriter(filePtah, true); //加true是追加 不加是覆盖String write = "哈哈哈";fileWriter.write(write.toCharArray()); //write(int)//write(char[])//write(char[], off, len)//write(sring)//write(string,off,len) fileWriter.close(); //一定要关闭 不然的话写不进去}