简体   繁体   English

使用Java构造文件路径

[英]Construct File Path using Java

I am trying to create a file, but file path is constructed through String Concats that uses some internal variables and labels, I am getting following error : 我正在尝试创建文件,但是文件路径是通过使用一些内部变量和标签的String Concats构造的,出现以下错误:

Exception in thread "main" java.io.IOException: The filename, directory name, or volume label syntax is incorrect
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(Unknown Source)
    at CopyEJ.CopyEJ.main(CopyEJ.java:133)

Is there a standard approach to built such files ? 是否有构建此类文件的标准方法?

String s_path = text_dir + "\\" + time_stmp + "_" + "Session" + "_" + file_name;


        File ssw = new File(s_path);

        ssw.createNewFile();  //Errors Out here

This will help you: 这将帮助您:

String path = "D://abc" + filename+ ".txt";
System.out.println("Path--- " + path);
File file = new File(path);
file.createNewFile()

You need to create the folder ( directory ) first: 您需要首先创建文件夹( directory ):

String s_path = text_dir + "/" + time_stmp + "_" + "Session" + "_" + file_name;
File ssw = new File(s_path);

ssw.getParentFile().mkdirs();
ssw.createNewFile();

If You are using Java 1.7 you can rewrite it as follows: 如果您使用的是Java 1.7,则可以按以下方式重写它:

Path s_path = Paths.get(text_dir, time_stmp + "_" + "Session" + "_" + file_name);
Files.createDirectories(s_path.getParent());  
File ssw = s_path.toFile();
ssw.createNewFile();

Paths.get() will use default system path separator. Paths.get()将使用默认的系统路径分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM