Java – 组合字符串路径名不起作用

huangapple go评论50阅读模式
英文:

Java - Composing String pathnames doesn't work

问题

当处理以String格式表示的文件和目录路径时,我使用约定,即所有目录路径都以File.separator结尾。这使我可以在系统内轻松区分文件和目录,还允许我非常轻松地组合路径。

然而,Java不遵循这个约定。这意味着每次我从某个地方获取目录的路径时,都需要检查它是否以File.separator结尾,如果不是,就将字符串添加到路径中。看起来很简单,对吧?

但我无法让它工作。

pathOfCurrentDirectory()方法查找启动JVM的程序的目录,并返回其带有File.separator结尾的绝对路径。createLogFile()方法使用前面的方法来创建日志文件的绝对路径,如果需要,创建缺失的目录,创建文件,然后返回其绝对路径。

pathOfCurrentDirectory()中的检查使它看起来像是按预期以File.separator结尾的。而createLogFile()中的检查似乎并不是这样。到底发生了什么?

英文:

When manipulating the pathnames of files and directories in String format, I use the convention that all directories pathnames ends with File.separator. This gives me an easy in-system way to differentiate between files and directories, and also allow me to compose pathnames very easily.

Java however doesn't follow this convention. This means that every time I acquire the pathname of a directory from somewhere, I need to check if it ends with File.separator and, if not, add the string to the pathname. Seems easy, right?

I can't manage to make it work.

The method pathOfCurrentDirectory() finds the directory of the program that starts the JVM and returns its absolute pathname with File.separator at the end. The method createLogFile() uses the previous method to create the absolute pathname of the log file, creates the missing directory if needed, creates the file, and then returns its absolute pathname.

The checks in pathOfCurrentDirectory() make it looks like its output truly ends with File.separator as intended. The checks in createLogFile() make it seem like it does not. What is happening?

	public static String createLogFile() {
		String pathOfCurrentDirectory = pathOfCurrentDirectory();
		String logDirectory = pathOfCurrentDirectory + "Log" + File.separator;
		System.out.println();
		System.out.println("pathOfCurrentDirectory: " + pathOfCurrentDirectory
					+ "\n logDirectory = " + logDirectory);
		String path = logDirectory + "Log_" + LogUtilities.dateId() + ".log";
		System.out.println("logFile: " + path + "\n logFile.exists() = " + new File(path).exists());
		
		FilesUtility.createNewFile(new File(path));
		System.out.println("After creation, logFile.exists() = " + new File(path).exists());
		
		return path;
	}
	public static String pathOfCurrentDirectory() {
		String output = new File(System.getProperty("user.dir")).getAbsolutePath();
	//	System.out.println("Dir: " + output);
	//	System.out.println("File.separatorChar = " + File.separatorChar);
		System.out.println("Last char of dir: " + output.charAt(output.length()-1));
		System.out.println("modifiedDir = " + (output + File.separator));
		String newOutput = (output + File.separator);
		System.out.println("newOutput = " + newOutput);
		//	return output;
		if( output.charAt(output.length()-1) == File.separatorChar )
			 return newOutput;
		else return output; 
	}

答案1

得分: 2

Java有两个专门用于操作路径的类 - File和Path,如果您使用它们,几乎不需要使用File.separator,也不会出现字符串处理错误。

这展示了如何同时使用File和Path:

public static void main(String[] args) throws IOException
{
    Files.createDirectories(Path.of(pathOfCurrentDirectory(), "Log"));
    File f = createLogAsFile();
    Path p = createLogAsPath();
}

private static Path createLogAsPath() throws IOException
{
    Path path = Path.of(pathOfCurrentDirectory(), "Log", "Log_" + LogUtilities.dateId() + ".log");
    System.out.println("createLogAsPath " + path + "\nFiles.isRegularFile(path) = " + Files.isRegularFile(path));
    Files.createFile(path);
    System.out.println("After creation, Files.isRegularFile(path) = " + Files.isRegularFile(path));
    return path;
}

private static File createLogAsFile() throws IOException
{
    File logDirectory = new File(pathOfCurrentDirectory(), "Log");
    File path = new File(logDirectory, "Log_" + LogUtilities.dateId() + ".log");
    System.out.println("createLogAsFile: " + path + "\n logFile.exists() = " + path.exists());
    path.createNewFile();
    System.out.println("After creation, logFile.exists() = " + path.exists());
    return path;
}

public static String pathOfCurrentDirectory() {
    return System.getProperty("user.dir");
}

是否使用File或Path版本取决于您的其他代码,但它们之间很容易通过toPath或toFile调用进行切换。

英文:

Java has 2 classes specifically for manipulating pathnames - File and Path, if you use these you will hardly ever need to use File.separator and risk String handling errors.

This shows using both File and Path:

public static void main(String[] args) throws IOException
{
    Files.createDirectories(Path.of(pathOfCurrentDirectory(), "Log"));
    File f = createLogAsFile();
    Path p = createLogAsPath();
}
private static Path createLogAsPath() throws IOException
{
    Path path = Path.of(pathOfCurrentDirectory(), "Log", "Log_" + LogUtilities.dateId() + ".log");
    System.out.println("createLogAsPath " + path + "\nFiles.isRegularFile(path) = " + Files.isRegularFile(path));
    Files.createFile(path);
    System.out.println("After creation, Files.isRegularFile(path) = " +Files.isRegularFile(path));
    return path;
}
private static File createLogAsFile() throws IOException
{
    File logDirectory = new File(pathOfCurrentDirectory(), "Log");
    File path = new File(logDirectory, "Log_" + LogUtilities.dateId() + ".log");
    System.out.println("createLogAsFile: " + path + "\n logFile.exists() = " + path.exists());
    path.createNewFile();
    System.out.println("After creation, logFile.exists() = " +path.exists());
    return path;
}
public static String pathOfCurrentDirectory() {
    return System.getProperty("user.dir");
}

Whether you use the File or Path version would depend on you other code thoug they are easy to switch between with toPath or toFile calls.

答案2

得分: 0

你可以真的用以下代码替换你的 createLogFile()

String filename = String.format("Log_%s.log", LogUtilities.dateId());
Path logfile = Paths.get("Log", filename);
FilesUtility.createNewFile(logfile.toFile());
英文:

You can really replace your createLogFile() with

String filename = String.format("Log_%s.log", LogUtilities.dateId());
Path logfile = Paths.get("Log", filename); 
FilesUtility.createNewFile(logfile.toFile());

huangapple
  • 本文由 发表于 2020年7月21日 19:30:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63013554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定