在 Ubuntu 中使用 Java 创建文件夹和文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20066413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:48:43  来源:igfitidea点击:

Create a folder and a file with Java in Ubuntu

javafileubuntudirectory

提问by Shahe Masoyan

Here is what I wanna do:

这是我想做的:

  1. Check if a folder exists
  2. If it does not exists, create the folder
  3. If it doest exists do nothing
  4. At last create a file in that folder
  1. 检查文件夹是否存在
  2. 如果不存在,则创建文件夹
  3. 如果它不存在什么都不做
  4. 最后在该文件夹中创建一个文件

Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code:

在 Windows 7 中一切正常,但是当我在 Ubuntu 中运行该应用程序时,它不会创建文件夹,它只是使用文件夹名称创建文件,例如:(我的文件名为 xxx.xml,文件夹为 d :\temp,因此在 Ubuntu 中,该文件在 d: 处生成,名称为 temp\xxx.xml)。这是我的代码:

File folder = new File("D:\temp");
if (folder.exists() && folder.isDirectory()) {
} else {
    folder.mkdir();
}

String filePath = folder + File.separator;
File file = new File(filePath + "xxx.xml");

StreamResult result = new StreamResult(file);
transformer.transform(source, result);
// more code here 

回答by Jean-Rémy Revy

You directory (D:\temp) is nos appropriate on Linux.

您的目录 (D:\temp) 不适用于 Linux。

Please, consider using linux File System, and the File.SEPARATOR constant :

请考虑使用 linux 文件系统和 File.SEPARATOR 常量:

static String OS = System.getProperty("OS.name").toLowerCase();
String root = "/tmp";

if (OS.indexOf("win") >= 0) {
    root="D:\temp";
} else {
    root="/";
}

File folder = new File(ROOT + "dir1" + File.SEPARATOR + "dir2");

if (folder.exists() && folder.isDirectory()) {
} else {
    folder.mkdir();
}

Didn't tried it, but whould work.

没试过,但行得通。

回答by codeMan

D:\tempdoes not exists in linux systems (what I mean is it interprets it as if it were any other foldername)

D:\temp在 linux 系统中不存在(我的意思是它将它解释为任何其他文件夹名称)

In Linux systems the file seperator is /instead of \as in case of Windows

在 Linux 系统中,文件分隔符/代替\了 Windows

so the solution is to :

所以解决方案是:

File folder = new File("/tmp"); 

instead of

代替

File folder = new File("D:\temp");

回答by Henry

Linux does not use drive letters (like D:) and uses forward slashes as file separator.

Linux 不使用驱动器号(如 D:)并使用正斜杠作为文件分隔符。

You can do something like this:

你可以这样做:

File folder = new File("/path/name/of/the/folder");
folder.mkdirs(); // this will also create parent directories if necessary
File file = new File(folder, "filename");
StreamResult result = new StreamResult(file);

回答by Michael Kazarian

On Unix-like systems no logical discs. You can try create on /tmpor /homeBelow code for create tempdirrectory in your home directory:

在类 Unix 系统上没有逻辑磁盘。您可以尝试在主目录中 创建目录/tmp/home以下代码temp

String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("user.home"):"D:\";
  System.out.println(myPathCandidate);
  //Check write permissions
  File folder = new File(myPathCandidate);
  if (folder.exists() && folder.isDirectory() && folder.canWrite()) {
      System.out.println("Create directory here");
  } else {System.out.println("Wrong path");}

or, for /tmp- system temp dicecrory. Majority of users can write here:

或者,对于/tmp- 系统临时目录。大多数用户可以在这里写:

String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("java.io.tmpdir"):"D:\";

回答by Joop Eggen

Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class Files.

在 Java 7 之前,文件 API 有一些可能性来创建临时文件,利用操作系统配置(如 RAM 磁盘上的临时文件)。由于 Java 7 使用实用程序函数类Files

回答by Alejandro Ruiz Arias

Consider both solutions using the getProperty static method of System class.

考虑使用 System 类的 getProperty 静态方法的两种解决方案。

String os = System.getProperty("os.name");

if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0 ) // Unix
    File folder = new File("/home/tmp"); 
else if(os.indexOf("win") >= 0) // Windows
    File folder = new File("D:\temp");
else
    throw Exception("your message");

回答by Tarek

Since Java 7, you can use the Filesutility class, with the new Pathclass. Note that exception handling has been omitted in the examples below.

从 Java 7 开始,您可以使用Files实用程序类和新的Path类。请注意,以下示例中省略了异常处理。

// uses os separator for path/to/folder.
Path file = Paths.get("path","to","file");

// this creates directories in case they don't exist
Files.createDirectories(file.getParent());

if (!Files.exists(file)) {
    Files.createFile(file);
}

StreamResult result = new StreamResult(file.toFile());
transformer.transform(source, result);

this covers the generic case, create a folder if it doesn't exist and a file on that folder.

这涵盖了一般情况,如果文件夹不存在,则创建一个文件夹,并在该文件夹中创建一个文件。



In case you actually want to create a temporary file, as written in your example, then you just need to do the following:

如果您确实想创建一个临时文件,如您的示例中所写,那么您只需要执行以下操作:

// this create a temporary file on the system's default temp folder.
Path tempFile = Files.createTempFile("xxx", "xml");

StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE));
transformer.transform(source, result);

Note that with this method, the file name will not correspond exactly to the prefix you used (xxx, in this case).

请注意,使用此方法,文件名将与您使用的前缀(xxx在本例中为 )不完全对应。

Still, given that it's a temp file, that shouldn't matter at all. The DELETE_ON_CLOSE guarantees that the file will get deleted when closed.

尽管如此,鉴于它是一个临时文件,这根本无关紧要。DELETE_ON_CLOSE 保证文件在关闭时将被删除。