輸入輸出流
阿新 • • 發佈:2020-11-18
java中流的簡單應用
知識點一:從網上讀取某一網址內容後寫入到一個檔案
public class BufferedTest { public void test() throws IOException { URL url =new URL("https://www.baidu.com/"); InputStream inputStream =url.openStream(); InputStreamReader inputStreamReader =new InputStreamReader(inputStream); BufferedReader bufferedReader =new BufferedReader(inputStreamReader); FileOutputStream fileOutputStream =new FileOutputStream("E:/io/test.html"); OutputStreamWriter outputStreamWriter =new OutputStreamWriter(fileOutputStream); BufferedWriter bufferedWriter =new BufferedWriter(outputStreamWriter); String s=new String(); while ((s=bufferedReader.readLine())!=null){ bufferedWriter.write(s); } bufferedReader.close(); bufferedWriter.close(); System.out.println("ok"); } public static void main(String[] args) throws IOException { BufferedTest bufferedTest =new BufferedTest(); bufferedTest.test(); } }
知識點二:用位元組流讀入讀出檔案內容:
File file =new File("E:/io/ioTest.txt"); FileInputStream fileInputStream =new FileInputStream(file); FileOutputStream fileOutputStream =new FileOutputStream("E:/io/huahua.txt"); byte[] bytes =new byte[1024]; int num; while ((num=fileInputStream.read(bytes))!=-1){ String s=new String(bytes, 0, num); fileOutputStream.write(bytes, 0, num); }
知識點三:用字元流讀入讀出檔案內容:
File file =new File("E:/io/ioTest.txt"); FileReader fileReader =new FileReader(file); FileWriter fileWriter =new FileWriter("E:/io/test.txt"); char[] chars=new char[1024]; int num=0; while ((num=fileReader.read(chars))!=-1){ String s=new String(chars, 0, num); fileWriter.write(s); } fileReader.close(); fileWriter.close();