在Java中如何读写文件

Java将数据写入文件:

String filepath ="C:\test.txt";
try (FileOutputStream fos = new FileOutputStream(filepath)){
     byte[] buffer = "hello world text".getBytes();
     fos.write(buffer, 0, buffer.length);
} catch (FileNotFoundException e) {
     e.printStackTrace();
} catch (IOException e) {
     e.printStackTrace();
}

Java从文本文件中读取数据

String filepath ="C:\test.txt";
try (FileInputStream fis = new FileInputStream(filepath)){    
     int length = (int) new File(filepath).length();
     byte[] buffer = new byte[length];
     fis.read(buffer, 0, length);
} catch (FileNotFoundException e) {
     e.printStackTrace();
} catch (IOException e) {
     e.printStackTrace();
}
日期:2020-06-02 22:15:22 来源:oir作者:oir