java获取文件的路径怎么写_Java获取文件路径常用方法解析

1. 前言

Java 开发中我们经常要获取文件的路径,比如读取配置文件等等。今天我们就关于文件的路径和如何读取文件简单地探讨一下。

2. 文件的路径

文件的路径通常有 相对路径 与 绝对路径。

2.1 相对路径

以当前文件为基准进行一级级目录指向被引用的资源文件。在 Java 代码中以当前运行的代码所在的位置为参照位置,只要被引用的文件相对于引用的文件的位置不变就可以被读取到。一旦改变相对位置就无法被读取到。

2.2 绝对路径

文件在文件系统中真正存在的路径,是指从硬盘的根目录(Windows为盘符)开始,进行一级级目录指向文件(从根目录一层层读写)。绝对路径顾名思义就是绝对的地址,就像你只要告诉别人你家的门牌号,他就能找到你家。而不是相对位置你告诉他在老王家的隔壁一样。

2.3 路径速记符

我们经常看到一些文件目录路径使用一些符号来简写,这里有必要总结一下(以类 Unix系统为例):

标识符

说明

../

表示当前文件所在的目录的上一级目录

./

表示当前文件所在的目录

/

表示根目录

~

当前用户目录, mac 下为 /Users/username,而 win10下为c:\users\username

Windows 下基本将 / 改为 \ 即可。

3. Java 中读取文件

我们先来声明一个测试路径:

foo

|_src

| |_Test.java

| |_app.yml

其中 Test.java 用来编写读取 app.yml 文件的逻辑。Java 中通过java.io.File 来进行文件操作。并且提供了以下三个方法来获取文件的路径。

3.1 getPath

该方法返回文件抽象路径名的字符串形式。实际上就是传递给 File 构造函数的路径名。

因此,如果 File 对象是使用相对路径创建的,则返回的值也将是相对路径。如果是绝对路径就返回绝对路径。

File file = new File("./app.yml");

# 输出 path = ./app.yml

System.out.println("path = " + file.getPath());

# 如果为绝对路径

File file = new File("/Users/dax/IdeaProjects/foo/src/app.yml");

# 输出 path = path = /Users/dax/IdeaProjects/foo/src/app.yml

System.out.println("path = " + file.getPath());

3.2 getAbsolutePath

该方法返回文件的绝对路径。请注意!这里是有大坑的。如果你的文件在 Java 工程内,路径是按照编译后的路径计算的。

File file = new File("./app.yml");

# absolutePath = /Users/dax/IdeaProjects/foo/./app.yml

System.out.println("absolutePath = " + absolutePath);

同时我们发现该方法只解析当前目录(上面代码所在的目录)的相对路径,如果初始化中的路径包含了 2.3 章节 中的 速记符 ,速记符 将不会被解析。

因为速记符的存在,一个文件在文件系统中的 绝对路径 可以有很多个。

3.3 getCanonicalPath

速记符 不被解析有时候是很痛苦的事,我们可能需要知道具体的路径。getCanonicalPath() 方法解决了这个问题。

File file = new File("./app.yml");

# canonicalPath = /Users/dax/IdeaProjects/foo/app.yml

System.out.println("canonicalPath = " + file.getCanonicalPath());

由于getCanonicalPath()读取的是文件系统,因此会降低性能。如果我们确定没有使用速记符,并且驱动器号大小写已标准化(如果使用Windows OS),我们应该首选使用getAbsoultePath(),除非你的项目中必须使用 getCanonicalPath()。

规范路径(不包含速记符)对于一个固定位置的文件来说是唯一的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
解析SVN路径下的.java文件获取改动方法,您可以使用JavaSVN库和JavaParser库。 JavaSVN库是一个Java库,用于访问Subversion存储库。您可以使用这个库来检索文件历史记录和版本信息。 JavaParser库是一个Java库,用于解析和分析Java源代码。您可以使用这个库来解析.java文件获取文件中的方法。 以下是一个简单的示例代码,展示如何使用这两个库来实现这个任务: ```java import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.diff.Edit; import org.eclipse.jgit.diff.EditList; import org.eclipse.jgit.diff.RawText; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.eclipse.jgit.treewalk.TreeWalk; import com.github.javaparser.JavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.NodeList; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.stmt.Statement; public class SVNJavaParser { public static void main(String[] args) throws Exception { String repoUrl = "svn://example.com/svn/myproject"; String username = "myusername"; String password = "mypassword"; String filePath = "/src/main/java/com/example/MyClass.java"; String commitId = "12345"; Repository repository = SVNUtils.getRepository(repoUrl, username, password); RevWalk revWalk = new RevWalk(repository); ObjectId objectId = repository.resolve(commitId); RevCommit commit = revWalk.parseCommit(objectId); AbstractTreeIterator oldTreeParser = SVNUtils.prepareTreeParser(repository, commit.getParent(0)); AbstractTreeIterator newTreeParser = SVNUtils.prepareTreeParser(repository, commit); List<DiffEntry> diffs = new Git(repository).diff() .setOldTree(oldTreeParser) .setNewTree(newTreeParser) .call(); for (DiffEntry entry : diffs) { if (entry.getNewPath().equals(filePath)) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DiffFormatter formatter = new DiffFormatter(outputStream); formatter.setRepository(repository); formatter.format(entry); String diffString = outputStream.toString(); RawText oldRawText = new RawText(diffString.split("@@")[0]); RawText newRawText = new RawText(diffString.split("@@")[2]); EditList editList = new EditList(); editList.addAll(new EditList(oldRawText, newRawText).getEdits()); TreeWalk treeWalk = new TreeWalk(repository); treeWalk.addTree(commit.getTree()); treeWalk.setRecursive(true); while (treeWalk.next()) { if (filePath.equals(treeWalk.getPathString())) { CanonicalTreeParser oldTreeParser2 = new CanonicalTreeParser(); ObjectId oldTree = commit.getParent(0).getTree(); try (ObjectReader reader = repository.newObjectReader()) { oldTreeParser2.reset(reader, oldTree); } String oldContent = new String(repository.open(treeWalk.getObjectId(0)).getBytes()); CompilationUnit oldCompilationUnit = JavaParser.parse(oldContent); CompilationUnit newCompilationUnit = null; for (Edit edit : editList) { int beginLine = edit.getBeginA(); int endLine = edit.getEndA(); if (beginLine < 0 || endLine < 0) continue; List<String> oldLines = new ArrayList<>(); for (int i = beginLine; i < endLine; i++) { oldLines.add(oldRawText.getString(i)); } String oldMethodContent = String.join("\n", oldLines); MethodDeclaration oldMethodDeclaration = getMethodDeclaration(oldCompilationUnit, oldMethodContent); if (oldMethodDeclaration == null) continue; int newBeginLine = edit.getBeginB(); int newEndLine = edit.getEndB(); if (newBeginLine < 0 || newEndLine < 0) continue; List<String> newLines = new ArrayList<>(); for (int i = newBeginLine; i < newEndLine; i++) { newLines.add(newRawText.getString(i)); } String newMethodContent = String.join("\n", newLines); if (newCompilationUnit == null) { String newContent = new String(repository.open(treeWalk.getObjectId(0)).getBytes()); newCompilationUnit = JavaParser.parse(newContent); } MethodDeclaration newMethodDeclaration = getMethodDeclaration(newCompilationUnit, newMethodContent); if (newMethodDeclaration == null) continue; System.out.println("Old method: " + oldMethodDeclaration.getNameAsString()); System.out.println("New method: " + newMethodDeclaration.getNameAsString()); } } } } } } private static MethodDeclaration getMethodDeclaration(CompilationUnit compilationUnit, String methodContent) { List<MethodDeclaration> methods = compilationUnit.findAll(MethodDeclaration.class); for (MethodDeclaration method : methods) { String methodString = method.toString(); if (methodString.equals(methodContent)) { return method; } } return null; } } ``` 在这个示例代码中,我们首先使用JavaSVN库来检索指定提交的特定文件的差异。然后,我们使用JavaParser库来解析文件中的方法和新文件中的方法,并将它们进行比较,以获取改动方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值