① 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系統中可能存在差異,因此在跨平台項目中應謹慎使用這些方法。同時,建議在編寫代碼時考慮路徑的可讀性和安全性,避免硬編碼路徑。
在處理文件路徑時,務必考慮文件系統的限制和特殊字元,確保路徑的正確性和兼容性。此外,對於敏感文件和目錄,應採取適當的訪問控制措施,以防止意外訪問或修改。