Đường dẫn tương đối trong Java

Đây ai muốn  lấy hình hay xóa hình lấy file hay bất cứ j mà cần đường dẫn tương đối thì đây , mình đã thử và thành công :

   String dirPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/upload");

có ví dụ minh họa cho coi chơi luôn , cái này mình lấy đường dẫn tương đối để tìm thư mục chứa hình để xóa nhé :

public void xoahinh(Object hinh) {
        String tamhinh = "";
        int id = (int) hinh;
        try {
// chuổi kết nối , nhớ add thư viện jdbc4.jar nhé
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection con = DriverManager.getConnection(ServerConnectString, "sa", "sa");
            PreparedStatement comm = con.prepareStatement("select image from news where newsid = '" + id + "'");
            ResultSet rs =comm.executeQuery();
           
            while(rs.next()){
            tamhinh = rs.getString(1);
            }
// nhớ mổi lần làm xong việc gì cũng phải đóng kết nối ko thôi dễ bị treo server lắm.
            con.close();
        } catch (Exception e) {

        }
        String dirPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/"+tamhinh);
//in ra thử koi có lấy được đường dẫn ko      
 System.out.println(dirPath);

        try {
//gọi hàm delete để kiểm tra có xóa được file chưa
            delete(new File(dirPath));
        } catch (Exception ex) {

        }

    }
// chỉ kiểm thử if else coi có xóa được hay chưa thôi
 public void delete(File file) {
        if (file.exists() == false) {
system.out.print('khong tim thay file');
        } else if (file.delete() == false) {

system.out.print('loi');
        } else {

system.out.print('xoa đuoc');
        }
    }

Comments

Bài đăn phổ biến

Tính Bình Phương 1 Số Trong Python

Deploy website lên VPS hoặc Hosting với Gitlab CI/CD

Đổi tên "READ MORE" trong bài post

MỞ CAMERA VÀ CHỤP ẢNH BẰNG PHP