io类一些简单操作(复习)

本文提供了一个Java IO操作的基本示例,包括创建目录、创建文件、删除文件及文件复制等常见任务。通过具体代码展示了如何使用Java进行文件管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java中提供了io类库,可以轻松的用java实现对文件的各种操作。

最近复习一下io类的一些常用的方法。 

import java.io.*;

class  FileTest
{
 public static void makeNewDir()
 {
  String filePath="C://测试1//";
  //filePath=filePath.toString();//中文转换
  File myFilePath=new File(filePath);
  if(!myFilePath.exists())
  myFilePath.mkdir();
 }

 public static void makeNewFile() throws Exception
 {
  String filePath="c://测试1//newFile.txt";
  //filePath=filePath.toString();
  File f=new File(filePath);
  if(!f.exists())
   f.createNewFile();
  FileWriter fw=new FileWriter(f);
  PrintWriter myFile=new PrintWriter(fw);
  String content1 ="这是测试数据1";
  String content2 ="这是测试数据2";
  //String strContent = content.toString();
  myFile.println(content1.toString());
  myFile.write(content2.toString());
  fw.close();
 }

 public static void deleteFile()
 {
  String filePath="c://测试1//newFile.txt";
  //filePath=filePath.toString();
  File myDelFile=new File(filePath);
  if(myDelFile.exists())
  { 
   myDelFile.delete();
   System.out.println(filePath+"删除成功!!!");
  }
  else
  {
   System.out.println(filePath+"该文件不存在");
  }
 }

 public static void copyFile() throws Exception
 {
  int bytesum=0;
  int byteread=0;
  //file:读到流中
  FileInputStream fis=new FileInputStream("c://测试1//newFile.txt");
  FileOutputStream fos=new FileOutputStream( "c://测试//copyFile.txt");
  byte[]  buffer =new  byte[2000];
  int length;
  while ((byteread=fis.read(buffer))!=-1)
   {
     System.out.println(byteread);
     bytesum+=byteread;
     System.out.println(bytesum);
     fos.write(buffer,0,byteread);
   }
  fis.close();
 }
 
 public static void main(String[] args)
 {
  System.out.println("Test File");
  makeNewDir();
  try
  {
   makeNewFile(); 
   copyFile();
  }
  catch (Exception ex)
  {
   ex.printStackTrace();
  }
  deleteFile();

 }
}

可以复制到EDITPULS自己试一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值