使用SeleniumWebdriver将文本复制到文件时出现编译错误的解决方案

Solution to compilation error on trying to copy text into a file using Selenium Webdriver

本文关键字:编译 错误 解决方案 文件 SeleniumWebdriver 文本 复制 使用      更新时间:2023-09-26

我是Selenium网络驱动程序的初学者。以下代码出现编译错误。。有人能帮忙吗?

我正在尝试将消息复制到文件中,而不是在控制台上显示它。

testResultFile="C:''CopyMessageTest.txt";
File file = new file(testResultFile).canWrite();
FileOutputStream fis = new FileOutputStream(file); 
PrintStream out = new PrintStream(fis);
System.setOut(out);
System.out.println("----------Sucessfully Logged In ----------------");

错误在线上

File file = new file(testResultFile).canWrite();

您在代码中很少犯错误。在第一行中,您没有提到它是什么类型的数据,它应该是一个字符串。在第二行中,您正在创建的对象应该是File类型,您提到了File,此外,canWrite()方法的返回类型是布尔值,如果您仍然想使用该提及,请在下一行中明确定义它。请参阅下面更正的代码。

    String testResultFile="C:''CopyMessageTest.txt";
    File file = new File(testResultFile);
    file.canWrite();
    FileOutputStream fis = new FileOutputStream(file); 
    PrintStream out = new PrintStream(fis);
    System.setOut(out);
    System.out.println("----------Sucessfully Logged In ----------------");

新文件(testResultFile).canWrite();将返回布尔值以检查我们是否可写。你必须用这种方式来检查

boolean  bool = new file(testResultFile).canWrite();

要简单地写入文件,您可以使用

   FileOutputStream fop = null;
    File file;
    String content = "This is the text content";
    try {
        file = new File("c:/newfile.txt");
        fop = new FileOutputStream(file);
        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }
        // get the content in bytes
        byte[] contentInBytes = content.getBytes();
        fop.write(contentInBytes);
        fop.flush();
        fop.close();
        System.out.println("Done");
    } catch (Exception e) {
        e.printStackTrace();
    }

根据评论以另一种方式更新

   import java.io.File;
   import java.io.FileNotFoundException;
   import java.io.FileOutputStream;
   import java.io.PrintStream;
 public class PrintTest {
public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub

    File file=new File("C:''CopyMessageTest.txt"); //my file where i want to write
    boolean bool = file.canWrite(); //cross checking file can be writable or not
    if(bool==false){
        file.setWritable(true); //if not writable then set it to writable
    }
    FileOutputStream fis = new FileOutputStream(file); 
    PrintStream out = new PrintStream(fis);
    System.setOut(out);
    System.out.println("----------Sucessfully Logged In ----------------");

    }
 }

谢谢,Murali