You must save the line to a file. Here is the way I write to the file:

if (sc==6){ System.out.println("Введите новую книгу:"); Scanner console = new Scanner(System.in); try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Lib.txt")))){ out.println(console); }catch (IOException e){ System.err.println(e); } } 

But I can't even write anything, it automatically saves some incomprehensible message to the file.

 java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\ ][decimal separator=\,][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]" 

    2 answers 2

    In the file, he writes exactly what you gave him - the scanner object. It is necessary to first consider the scanner input, and already output it to a file:

     String str = console.nextLine() ... out.println(str); 

    Besides, are you sure that you need a scanner at all? Maybe you have enough console?

     import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.Console; public class ConsoleDemo { public static void main(String[] args) throws IOException { Console console = System.console(); String s = console.readLine(); try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Lib.txt")))) { out.println(s); } catch (IOException e) { System.err.println(e); } } } 

      You stream the object , not the data from it:

       if (sc == 6) { System.out.println("Введите новую книгу:"); Scanner console = new Scanner(System.in); try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Lib.txt")))) { out.println(console.next()); } catch (IOException e) { System.err.println(e); } } 

      notice the line: out.println(console.next()); calling the method .next() returns a string representation of the incoming stream, taking into account the separator. I will add that it is worth using the hasNext() method which is worth checking for the presence of residual data (As an example, when you enter a line like: "first \ r \ n second \ r \ n third \ r \ n" only first will be entered in the log file)