When you open a text(.txt) file in a browser and check the structure of the contents in the console, you will notice that it's HTML and the content of the file are enclosed within <pre></pre>
tag.
So what you can do is switch to the new tab (since you are opening the file in new tab) and then user getText()
to fetch the content of the <pre></pre>
tag.
Here is a sample code I tried and it worked:
public static void main(String[] args) {
try {
WebDriver driver;
//System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "//chromedriver");
//driver = new ChromeDriver();
System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "//geckodriver");
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://localhost/1/test.html");
driver.manage().window().maximize();
Thread.sleep(2000);
String s = null;
driver.findElement(By.tagName("a")).click();
Thread.sleep(2000);
ArrayList tabs = new ArrayList (driver.getWindowHandles());
driver.switchTo().window((String) tabs.get(1));
String filecontent = driver.findElement(By.tagName("pre")).getText();
System.out.println(filecontent);
Thread.sleep(5000);
driver.close();
driver.quit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}