Java:如何在Mac OS X中创建新文件夹 [英] Java: How to create a new folder in Mac OS X

查看:1183
本文介绍了Java:如何在Mac OS X中创建新文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在ex中创建一个文件夹.我在Mac OS X中的桌面

I want to create a folder in ex. my desktop in Mac OS X

我尝试使用此代码,当然我的名字不是Mymac:)

I try to use this code, instead of Mymac is my name of course:)

String path="/Users/Mymac/Desktop";
String house = "My_home";
File file=new File(path);
if(!file.exists())
    file.mkdirs(); // or file.mkdir()

file=new File(path + "/" + house);   
try {
  if(file.createNewFile())
   {
   }
} catch (IOException ex) {

  ex.printStackTrace();
}

您知道如何创建新文件夹吗? 另一件事是,当我想在我的代码所在的目录中创建一个文件夹时,您知道我该怎么写吗?我尝试过

Do you know how I could create a new folder? And another thing is when I want to create a folder in the directory where my code is, do you know how I could write that? I have tried

   String path="./";

   String path="::MyVolume";

   String path=".";

推荐答案

查找其中一个类所在的文件夹/目录(假设它们不在Jar中),然后在其中创建子文件夹:

To find the folder/directory where one of your classes is (assuming they are not in a Jar), and then to create a subfolder there:

    String resource = MyClass.class.getName().replace(".", File.separator) + ".class";      
    URL fileURL = ClassLoader.getSystemClassLoader().getResource(resource);

    String path = new File(fileURL.toURI()).getParent();
    String mySubFolder = "subFolder";
    File newDir = new File(path + File.separator + mySubFolder);
    boolean success = newDir.mkdir();

(上面的代码可以做得更紧凑,我更详细地列出了它,以演示所有步骤.)当然,您需要关注权限问题.确保正在运行Java的用户具有创建新文件夹的权限.

(The code above could be made more compact, I listed it more verbosely to demonstrate all the steps.) Of course, you need to be concerned about permission issues. Make sure that the user which is running java has permission to create a new folder.

这篇关于Java:如何在Mac OS X中创建新文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆