如何在同一个类的另一个方法中使用由一个方法返回的文件。

huangapple 未分类评论61阅读模式
标题翻译

how to use file return by 1 method into another method of the same class

问题

Step1: 用户点击按钮,文件开始下载。

Step2: 下载的PDF文件内容被读取。

预期: 在下载文件之前,如果文件已经存在,则删除文件。

尝试过的代码:

public File A() {
    String userDir = System.getProperty("user.home") + "\\Downloads";
    File file = new File(userDir + "\\PDFStatement.pdf");
    return file;
}

public void clickxxxButton() {
    try {
        File f = pst.A();
        if (f.exists()) // 在下载之前删除已存在的文件
        {
            f.delete();
        }
    } catch (Exception e) {
        e.getMessage();
    }
    clickOn(xxxxButton); // 在这里,PDF文件开始下载
}

public void verifyPDFContents() {
    try {

        // 加载现有的文档
        File file = pst.A(); // 这里的 pst 是同一个类的对象,该方法所在的类
        PDDocument document = PDDocument.load(file);

        // 实例化 PDFTextStripper 类
        PDFTextStripper pdfStripper = new PDFTextStripper();

        // 从 PDF 文档中提取文本
        String text = pdfStripper.getText(document);
        System.out.println(text);

        // 关闭文档
        document.close();
        file.delete();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我遇到了关于页面对象依赖注入的错误。然而,如果我将所有内容(除了删除操作)放在 verifyPDFContents 方法内部(例如,声明和创建文件),那么代码能够正常工作。

英文翻译

Step1: user clicks on a button file gets downloaded.

Step2: contents of that pdf is read.

Expected : before downloading delete the file if it already exists

tried :

    public File A() {
		String userDir = System.getProperty("user.home")+"\\Downloads";
		File file = new File(userDir+"\\PDFStatement.pdf");
		return file;
	}

	public void clickxxxButton() {
		try {
			File f=pst.A();
			if (f.exists()) // to delete the already existing file before downloading
            {
				f.delete();
			}
		}
		catch (Exception e){
			e.getMessage();
		}
		clickOn(xxxxButton);// here pdf file gets downloaded
	}
 
    
    public void verifyPDFContents() {
		try {
						
			//Loading an existing document
		     			
			File file =pst.A();// here pst is the object of the same class where this method resides
		      
			PDDocument document = PDDocument.load(file);
		      //Instantiate PDFTextStripper class
		      PDFTextStripper pdfStripper = new PDFTextStripper();

		      //Retrieving text from PDF document
		      String text = pdfStripper.getText(document);
		      System.out.println(text);

		      //Closing the document
		      document.close();
              file.delete() 
		}
		 catch (IOException e) {			
			e.printStackTrace();
		}
	}	

I am getting error for pageobject dependency injection. While if i have everything (except the delete )inside verifypdfcontent(like declaring and creating the file),it works fine

huangapple
  • 本文由 发表于 2020年3月4日 03:08:19
  • 转载请务必保留本文链接:https://java.coder-hub.com/60514006.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定