Java - Put the content of a txt file in a String using Scanner class -
i have example txt file:
this example file.
i want put content of file in string using scanner class. resolved problem follows:
try { scanner s = new scanner(new file("example.txt")); string filecontent = new string(); int = 0; while(s.hasnextline()) { if(i !=0) { filecontent += "\n"; } filecontent += s.nextline(); i++; } } catch(filenotfoundexception e) { }
if didn't put line on if:
filecontent += "\n";
i string begins \n
, that's not want, because want have same content of file in filecontent string.
there better way want? important me use scanner class.
thanks!
try if need string, try like:
string content = s.usedelimiter("\\z").next(); system.out.println(content);
Comments
Post a Comment