Mình có 1 file test.xlsx ở desktop. Click đúp vào file để mở lên. Vậy có cách nào để 1 chương trình java có thể thao tác dc với file test.xlsx mà ko biết file path của nó ko. Chỉ biết rằng nó đang dc mở .
Java làm sao để get dc file path của những file đang mở
Câu hỏi của bạn rất vô lý. Nếu đã biết nó ở desktop rồi thì cần gì tìm path ?
Mình hiểu là tìm fileName của những file excel đang mở.
b1: List all file ở desktop rồi chọn ra các file có đuôi excel xls, xlsx …
public class ListFilesUtil {
/**
* List all the files and folders from a directory
* @param directoryName to be listed
*/
public void listFilesAndFolders(String directoryName){
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList){
System.out.println(file.getName());
}
}
/**
* List all the files under a directory
* @param directoryName to be listed
*/
public void listFiles(String directoryName){
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
System.out.println(file.getName());
}
}
}
/**
* List all the folder under a directory
* @param directoryName to be listed
*/
public void listFolders(String directoryName){
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isDirectory()){
System.out.println(file.getName());
}
}
}
/**
* List all files from a directory and its subdirectories
* @param directoryName to be listed
*/
public void listFilesAndFilesSubDirectories(String directoryName){
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()){
listFilesAndFilesSubDirectories(file.getAbsolutePath());
}
}
}
public static void main (String[] args){
ListFilesUtil listFilesUtil = new ListFilesUtil();
final String directoryWindows ="C:\\Users\\QuanDT\\Desktop\\";
listFilesUtil.listFiles(directoryWindows );
}
}
b2: kiểm tra các file excel đó có file nào đang mở
String fileName = "C:\\Users\\QuanDT\\Desktop\\Text.xlsx";
File file = new File(fileName);
// try to rename the file with the same name
File sameFileName = new File(fileName);
if(file.renameTo(sameFileName)){
// if the file is renamed
System.out.println("file is closed");
}else{
// if the file didnt accept the renaming operation
System.out.println("file is opened");
}
b3: Có file đang open rồi thì làm tiếp việc của bạn.
2 Likes
tại thư viện bên c# có thể attack trực tiếp vào file excel đang active
còn bên thư viện apache poi của java ko làm dc nên mình mới phải hỏi như thế
Câu trả lời của mình đã đúng yêu cầu của bạn chưa?
đó cũng là 1 giải pháp
thanks bạn
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?