Java建立檔案夾與建立檔案

來源:互聯網
上載者:User
// author:         [email]huapingsmith@hotmail.com[/email]
// description:     程式先檢查檔案夾是否存在,如果不存在,則建立一個,存在,則繼續運行.
//               檔案夾處理完成後,下一步工作為往檔案夾中建立檔案.
// caution:       當前檔案夾中如果已經有名為abc.txt的檔案時,
//               在當前檔案夾建立一個名為abc.txt的檔案會失敗.
//               在這個程式中,如果E://test 下已經有名為1,2,3,4的檔案時,程式執行會失敗.

import java.io.*;

public class Demo
{
  public static void main( String[] args)
  {
    File   dirFile;
    File   tempFile;
    boolean bFile;
    String   sFileName;
   
    bFile = false;

    try
    {
        dirFile = new File("E://test");
        bFile   = dirFile.exists();

        if( bFile == true )
        {
          System.out.println("The folder exists.");
        }
        else
        {
          System.out.println("The folder do not exist,now trying to create a one...");
          bFile = dirFile.mkdir();
          if( bFile == true )
          {
            System.out.println("Create successfully!");
          }
          else
          {
            System.out.println("Disable to make the folder,please check the disk is full or not.");
            System.exit(1);
          }
        }
     
        System.out.println("Now we put files in to the folder...");

        for(int i=0; i<5; i++)
        {
          sFileName = new String("E://test//");
          sFileName += String.valueOf(i);
          tempFile = new File(sFileName);
          bFile = tempFile.createNewFile();
        }
      }catch(IOException e)
      {
        // Exception hadler
      }
     
      if( bFile == true )
        System.out.println("Successfully put files in to the folder!");
      else
        System.out.println("Sorry sir,i don't finish the job!");
  }
} 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.