如何使用Java进行文件操作,包括读写及删除?

原创 爱被打了一巴掌 2024-10-16 06:27 128阅读 0赞

在Java中,我们可以使用java.io包下的类来进行文件操作。以下是主要的一些操作:

  1. 创建文件

    1. File file = new File("path_to_file");
    2. // 如果文件存在则抛出异常
    3. file.createNewFile();
  2. 读写文件内容

  • 读取文件内容
    1. String content = new String(new FileInputStream(file)));
  • 写入文件内容
    1. try (BufferedWriter writer = new BufferedWriter(new FileWriter(file)))) {
    2. writer.write("Your content here");
    3. }
    4. catch (IOException e) {
    5. e.printStackTrace();
    6. }
  1. 删除文件
    1. file.delete();
    请确保提供正确的路径,否则可能会抛出异常。
文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,128人围观)

还没有评论,来说两句吧...

相关阅读