① java怎样获取当前路径
java获取当前路径的几种方法
1、利用System.getProperty()函数获取当前路径:
System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径
2、使用File提供的函数获取当前路径:
File directory = new File("");//设定为当前文件夹
try{
System.out.println(directory.getCanonicalPath());//获取标准的路径
System.out.println(directory.getAbsolutePath());//获取绝对路径
}catch(Exceptin e){}
File.getCanonicalPath()和File.getAbsolutePath()大约只是对于new File(".")和new File("..")两种路径有所区别。
# 对于getCanonicalPath()函数,“."就表示当前的文件夹,而”..“则表示当前文件夹的上一级文件夹
# 对于getAbsolutePath()函数,则不管”.”、“..”,返回当前的路径加上你在new File()时设定的路径
# 至于getPath()函数,得到的只是你在new File()时设定的路径
比如当前的路径为 C:/test :
File directory = new File("abc");
directory.getCanonicalPath(); //得到的是C:/test/abc
directory.getAbsolutePath(); //得到的是C:/test/abc
direcotry.getPath(); //得到的是abc
File directory = new File(".");
directory.getCanonicalPath(); //得到的是C:/test
directory.getAbsolutePath(); //得到的是C:/test/.
direcotry.getPath(); //得到的是.
File directory = new File("..");
directory.getCanonicalPath(); //得到的是C:/
directory.getAbsolutePath(); //得到的是C:/test/..
direcotry.getPath(); //得到的是..
② JAVA如何得到文件路径
用
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
public class FileChooserDemo extends JPanel {
static final long serialVersionUID = 5854418136127725290L;
public class ExtensionFilter extends FileFilter {
private String extensions[];
private String description;
public ExtensionFilter(String description, String extension) {
this(description, new String[] { extension });
}
public ExtensionFilter(String description, String extensions[]) {
this.description = description;
this.extensions = (String[]) extensions.clone();
}
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
int count = extensions.length;
String path = file.getAbsolutePath();
for (int i = 0; i < count; i++) {
String ext = extensions[i];
if (path.endsWith(ext)
&& (path.charAt(path.length() - ext.length()) == '.')) {
return true;
}
}
return false;
}
public String getDescription() {
return (description == null ? extensions[0] : description);
}
}
public FileChooserDemo() {
JButton jb = new JButton("Open File Viewer");
add(jb);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser(".");
// chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
FileFilter type1 = new ExtensionFilter("Java source", ".java");
FileFilter type2 = new ExtensionFilter("Image files",
new String[] { ".jpg", ".gif", "jpeg", "xbm" });
FileFilter type3 = new ExtensionFilter("HTML files",
new String[] { ".htm", ".html" });
chooser.addChoosableFileFilter(type1);
chooser.addChoosableFileFilter(type2);
chooser.addChoosableFileFilter(type3);
chooser.setAcceptAllFileFilterUsed(true);
chooser.setFileFilter(type2); // Initial filter setting
int status = chooser.showOpenDialog(FileChooserDemo.this);
if (status == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
System.out.println(f);
}
}
};
jb.addActionListener(listener);
}
public static void main(String args[]) {
JFrame f = new JFrame("Enhanced File Example");
JPanel j = new FileChooserDemo();
f.getContentPane().add(j, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
③ 通过java获取当前项目路径
getClass().getResource() 方法获得相对路径( 此方法在jar包中无效。返回的内容最后包含/)
例如 项目在/D:/workspace/MainStream/Test
在javaProject中,getClass().getResource("/").getFile().toString() 返回:/D:/workspace/MainStream/Test/bin/
publicStringgetCurrentPath(){
//取得根目录路径
StringrootPath=getClass().getResource("/").getFile().toString();
//当前目录路径
StringcurrentPath1=getClass().getResource(".").getFile().toString();
StringcurrentPath2=getClass().getResource("").getFile().toString();
//当前目录的上级目录路径
StringparentPath=getClass().getResource("../").getFile().toString();
returnrootPath;
}
④ java瀵煎嚭鏂囦欢鏃惰╃敤鎴烽夋嫨璺寰勬庝箞寮勶紵
浣跨敤淇濆瓨鏂囦欢瀵硅瘽妗嗭細x0dx0ax0dx0a /**x0dx0a * 淇濆瓨x0dx0a */x0dx0aprivate void saveFile(){x0dx0aJFileChooser dialog = new JFileChooser();x0dx0adialog.setDialogTitle("鍙﹀瓨涓");x0dx0adialog.setFileSelectionMode(JFileChooser.FILES_ONLY);x0dx0adialog.setDialogType(JFileChooser.SAVE_DIALOG);x0dx0adialog.setFileFilter(new TextFileFilter("*.txt", "鏂囨湰鏂囨。(*.txt)"));x0dx0aint result = dialog.showSaveDialog(this);x0dx0aif(result == JFileChooser.APPROVE_OPTION){x0dx0aFile file = dialog.getSelectedFile();x0dx0afileName = file.getAbsolutePath();//寰楀埌鏂囦欢鍏ㄥ悕x0dx0a...x0dx0a}x0dx0a}x0dx0ax0dx0a闄勬枃鏈绫诲瀷杩囨护鍣锛歕x0dx0aimport java.io.File;x0dx0aimport java.util.ArrayList;x0dx0aimport javax.swing.filechooser.FileFilter;x0dx0ax0dx0a/**x0dx0a * 璁剧疆鏂囦欢鎵撳紑瀵硅瘽妗嗙殑鏂囦欢杩囨护鍣╘x0dx0a * @author developerx0dx0a */x0dx0apublic class TextFileFilter extends FileFilter {x0dx0aprivate ArrayList
⑤ java中获取文件路径的几种方式
File的getPath方法得到相对路径 getAbsolutePath方法得到绝对路径
举个例子
String fileName = "yourfile.txt";
File aFile = new File(fileName);//这里可以把路径拼在fileName前面 可以用相对路径 也可以用绝对 注意分隔符
System.out.println(aFile.getPath()); //相对路径
System.out.println(aFile.getAbsolutePath()); //绝对路径
具体的东西在这里 http://teamojiao.iteye.com/blog/446615
⑥ java中获取文件路径的几种方式
获取当前类的所在工程路径;如果未添加“/”,则代码如下:
File f = new File(this.getClass().getResource("").getPath());
System.out.println(f);
执行结果为:C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin\com\test
获取当前类的绝对路径;第二种方法为:
File directory = new File("");//参数为空
String courseFile = directory.getCanonicalPath() ;
System.out.println(courseFile);
执行结果为:C:\Documents and Settings\Administrator\workspace\projectName
获取当前类的所在工程路径;第三种方法为:
URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt");
System.out.println(xmlpath);
执行结果为:file:/C:/Documents%20and%20Settings/Administrator/workspace/projectName/bin/selected.txt
获取当前工程src目录下selected.txt文件的路径;第四种方法为:
System.out.println(System.getProperty("user.dir"));
执行结果为:C:\Documents and Settings\Administrator\workspace\projectName
获取当前工程路径;第五种方法为:
System.out.println(System.getProperty("java.class.path"));
执行结果为:C:\Documents and Settings\Administrator\workspace\projectName\bin
以上介绍了五种获取文件路径的方法,每种方法都有其特点和适用场景。第一种方法适用于需要获取类所在目录的路径,但结果包含bin文件夹;第二种方法适用于获取文件系统中的绝对路径;第三种方法适用于获取类加载器资源的URL路径,结果包含文件协议;第四种方法获取当前工作目录,即工程根目录;第五种方法获取类路径,通常指向编译后的类文件所在的目录。
在实际开发中,根据具体需求选择合适的方法。例如,如果需要获取源代码文件的路径,可以使用第三种方法;如果需要获取编译后的类文件路径,则使用第五种方法更为合适。
需要注意的是,路径格式在Windows和Linux系统中可能存在差异,因此在跨平台项目中应谨慎使用这些方法。同时,建议在编写代码时考虑路径的可读性和安全性,避免硬编码路径。
在处理文件路径时,务必考虑文件系统的限制和特殊字符,确保路径的正确性和兼容性。此外,对于敏感文件和目录,应采取适当的访问控制措施,以防止意外访问或修改。