java - Scanner only reading 1st token of a string -
new java language,
the following bit of code. whole string isn't written file. first token written file. explanations ?
import java.io.filewriter; import java.io.ioexception; import java.util.scanner; public class fichiertextewrite { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub try { system.out.println("entrez le nom d'un fichier :"); scanner in = new scanner(system.in); string filename = in.next(); filewriter fwrite = new filewriter(filename); system.out.println("entrez une phrase memoriser"); fwrite.write(in.next()); system.out.println("writing on file complete "); fwrite.close(); }catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
i have tried nextline()
method didn't seem help. forcefully wrote blank caracter , terminated program.
---edit---
i tried :
import java.io.filewriter; import java.io.ioexception; import java.util.scanner; public class fichiertextewrite { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub try { system.out.println("entrez le nom d'un fichier :"); scanner in = new scanner(system.in); string filename = in.next(); filewriter fwrite = new filewriter(filename); system.out.println("entrez une phrase memoriser"); fwrite.write(in.nextline()); system.out.println("writing on file complete "); fwrite.close(); }catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
if don't believe please compile , run program. doesn't work. doesn't let me input string , goes straight next instructions closes stream , output file written successfully.
you should use in.nextline()
whole line.
fwrite.write(in.nextline());
use nextline() both times:
import java.io.filewriter; import java.io.ioexception; import java.util.scanner; public class fichiertextewrite { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub try { system.out.println("entrez le nom d'un fichier :"); scanner in = new scanner(system.in); string filename = in.nextline(); // *** note change filewriter fwrite = new filewriter(filename); system.out.println("entrez une phrase memoriser"); fwrite.write(in.nextline()); system.out.println("writing on file complete "); fwrite.close(); }catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
otherwise nextline() call read end-of-line token first line, 1 file name, , don't want this.
Comments
Post a Comment