在Java中加入路径

时间:2015-12-25 02:16:26

标签: java

Python我可以使用os.path.join加入两条路径:

os.path.join("foo", "bar") # => "foo/bar"

我正试图在Java中实现同样的目标,而不必担心OSUnixSolaris还是Windows

public static void main(String[] args) {
    Path currentRelativePath = Paths.get("");
    String current_dir = currentRelativePath.toAbsolutePath().toString();
    String filename = "data/foo.txt";
    Path filepath = currentRelativePath.resolve(filename);

    // "data/foo.txt"
    System.out.println(filepath);

}

我希望Path.resolve( )加入我当前的目录/home/user/testdata/foo.txt制作/home/user/test/data/foo.txt。 我错了什么?

6 个答案:

答案 0 :(得分:74)

尽管使用empty String获取当前目录的原始解决方案仍然有效。但建议对当前目录使用user.dir属性,对主目录使用user.home

Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(), "data", "foo.txt");
System.out.println(filePath.toString());

输出:

/Users/user/coding/data/foo.txt

来自Java Path类文档:

  

如果Path仅包含一个名为empty的名称元素,则该路径被视为空路径。使用empty path is equivalent to accessing the default directory文件系统访问文件。

为什么Paths.get("").toAbsolutePath()有效

当空字符串传递给Paths.get("")时,返回的Path对象包含空路径。但是当我们调用Path.toAbsolutePath()时,它会检查路径长度是否大于零,否则它会使用user.dir系统属性并返回当前路径。

以下是Unix文件系统实现的代码:UnixPath.toAbsolutePath()

基本上,一旦解析了当前目录路径,就需要再次创建Path实例。

另外,我建议将File.separatorChar用于与平台无关的代码。

Path currentRelativePath = Paths.get("");
Path currentDir = currentRelativePath.toAbsolutePath(); // <-- Get the Path and use resolve on it.
String filename = "data" + File.separatorChar + "foo.txt";
Path filepath = currentDir.resolve(filename);

// "data/foo.txt"
System.out.println(filepath);

输出:

/Users/user/coding/data/foo.txt

答案 1 :(得分:15)

Paths#get(String first, String... more)州,

  

将路径字符串或字符串序列转换为Path时将其转换为System.getProperty("user.dir")

     

...

     

如果first为空,则返回表示路径的Path   string和more不包含任何非空字符串。

要获取当前用户目录,只需使用Path path = Paths.get(System.getProperty("user.dir"), "abc.txt"); System.out.println(path);

get

此外,String方法使用Path /test/inside/abc.txt,它将用于提供后续路径字符串。因此,要为Path path = Paths.get("/test", "inside", "abc.txt"); 创建@ECHO OFF SETLOCAL set file=%1 FOR %%i IN ("%file%") DO ( set prefix=%%~ni ) set outname=%prefix%-%%02d.pdf pdftk.exe %file% burst output %outname% ,您必须按以下方式使用它,

StringJoiner joiner = new StringJoiner(File.pathSeparator); //Separator
joiner.add("path1").add("path2");
String joinedString = joiner.toString();

答案 2 :(得分:9)

不是特定方法。

如果使用java 8或更高版本,则有2个选项:

a)使用java.util.StringJoiner

StringUtils.join(new Object[] {"path1", "path2"}, File.pathSeparator);

b)使用# api.py def foo(): pass def bar(): pass # main.py import api def register_api(server, api_obj): methods = dir(api_obj) apis = filter(lambda m: not m.startswith('_'), methods) [server.register_function(getattr(api_obj, api)) for api in apis] def main(): endpoint = (LISTEN_ADDR, LISTEN_PORT) server = SimpleJSONRPCServer(endpoint) register_api(server, api) server.serve_forever()

如果使用java 7或更低版​​本,则可以使用apache commons中的commons-lang库。 StringUtils类有一个使用分隔符连接字符串的方法。

c)public class MainActivity extends AppCompatActivity { public static final String TAG = "TAG"; ViewPager parentPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); initViews(); initData(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); } private void initViews() { parentPager = (ViewPager) findViewById(R.id.parent_pager); } private void initData() { List<ViewPager> pagers = new ArrayList<ViewPager>(); for(int j = 0; j < 3; j++) { List<LinearLayout> list = new ArrayList<LinearLayout>(); for (int i = 0; i < 5; i++) { LinearLayout layout = new LinearLayout(this); TextView textView = new TextView(this); textView.setText("This is the" + i + "th page in PagerItem" + j); layout.addView(textView); textView.setGravity(Gravity.CENTER); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams(); params.gravity = Gravity.CENTER; list.add(layout); } MyViewPagerAdapter adapter = new MyViewPagerAdapter(list); final ViewPager childPager = (ViewPager) LayoutInflater.from(this).inflate(R.layout.child_layout, null).findViewById(R.id.child_pager); childPager.setAdapter(adapter); childPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { Log.d(TAG, "onPageScrolled: position: " + position + ", positionOffset: " + positionOffset); } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); pagers.add(childPager); } MyParentViewPagerAdapter parentAdapter = new MyParentViewPagerAdapter(pagers); parentPager.setAdapter(parentAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } class MyViewPagerAdapter extends PagerAdapter { private List<LinearLayout> data; public MyViewPagerAdapter(List<LinearLayout> data) { this.data = data; } @Override public int getCount() { return data.size(); } @Override public int getItemPosition(Object object) { return data.indexOf(object); } @Override public Object instantiateItem(ViewGroup container, int position) { LinearLayout linearLayout = data.get(position); container.addView(linearLayout); return data.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { LinearLayout layout = data.get(position); container.removeView(layout); layout = null; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } } class MyParentViewPagerAdapter extends PagerAdapter { private List<ViewPager> data; public MyParentViewPagerAdapter(List<ViewPager> data) { this.data = data; } @Override public int getCount() { return data.size(); } @Override public int getItemPosition(Object object) { return data.indexOf(object); } @Override public Object instantiateItem(ViewGroup container, int position) { ViewPager pager = data.get(position); if(pager.getParent() != null) { ((ViewGroup) pager.getParent()).removeView(pager); } container.addView(pager); return data.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { ViewPager pager = data.get(position); container.removeView(pager); pager = null; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } } }

旁注:您可以使用linux pathseparator&#34; /&#34;对于Windows(请记住,绝对路径类似于&#34; / C:/ mydir1 / mydir2&#34;。如果使用诸如file://之类的协议,则使用always&#34; /&#34;非常有用

答案 3 :(得分:5)

最基本的方法是:

Path filepath = Paths.get("foo", "bar");

你永远不应该写Paths.get("")。我很惊讶这一点很有意义。如果要显式引用当前目录,请使用Paths.get(System.getProperty("user.dir"))。如果您想要用户的主目录,请使用Paths.get(System.getProperty("user.home"))

您还可以合并这些方法:

Path filepath = Paths.get(
    System.getProperty("user.home"), "data", "foo.txt");

答案 4 :(得分:1)

在Java中连接路径的最可靠,独立于平台的方法是使用Path::resolve(如Paths::get的JavaDoc中所述)。对于表示路径片段的任意长度的字符串数组,可以使用Java Stream将它们连接在一起:

private static final String[] pieces = {
    System.getProperty("user.dir"),
    "data",
    "foo.txt"};
public static void main (String[] args) {
    Path dest = Arrays.stream(pieces).reduce(
    /* identity    */ Paths.get(""),
    /* accumulator */ Path::resolve,
    /* combiner    */ Path::resolve);
    System.out.println(dest);
}

答案 5 :(得分:0)

你可以喜欢

// /root
Path rootPath = Paths.get("/root");
// /root/temp
Path temPath = rootPath.resolve("temp");

这里有一个很好的详细帖子Path Sample Usecase