How to input text in java using the comand console? - java

I would like to input a copied text from a text processor or others.
Using nextLine() just introduces the first line and it doesn't let me use StringBuffer too. I haven't found anything to solve my problem.
This is my code:
public static void main (String args[]) {
Scanner keyboard= new Scanner(System.in);
StringBuffer lines= new StringBuffer();
String line;
System.out.println("texto:");
line= keyboard.nextLine();
//lines= keyboard.nextLine(); //this doesn´t work
System.out.println(lines);
}
Here is an example of what I would like to do:
I copy this text from a text file:
ksjhbgkkg
sjdjjnsfj
sdfjfjjjk
Then, I paste it on the cmd (I use Geany).
I would like to be able to get a StringBuffer or similar (something I can manipulate) like this:
StringBuffer x = "ksjhbgkkgsjdjjnsfjsdfjfjjjk"
Thanks!

Try using something like:
while(keyboard.hasNextLine()) {
line = keyboard.nextLine();
}
You could then store those lines. (e.g. an array/ArrayList).

You can append the keyboard.nextLine() to your stringBuffer like so:
lines.append(keyboard.nextLine());
StringBuffer will accept a String to be appended so this should fit your purposes.
You could use this with the while loop as shown by #Cache which would give something like:
while (keyboard.hasNextLine()) {
lines.append(keyboard.nextLine());
}

#Cache Staheli has the right approach. To elaborate on how you can put the keyboard input into your StringBuffer, consider this:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
StringBuffer lines= new StringBuffer();
String line;
System.out.println("texto:");
while(keyboard.hasNextLine() ) { // while there are more lines to read
line = keyboard.nextLine(); // read the next line
if(line.equals("")) { // if the user entered nothing (i.e. just pressed Enter)
break; // break out of the input loop
}
lines.append(line); // otherwise append the line to the StringBuffer
}
System.out.println(lines); // print the lines that were entered
keyboard.close(); // and close the Scanner
}

Related

Read a single line from text file & not the entire file (using buffered reader)

I am trying to write a piece of code that reads a single line of text from a text file in java using a buffered reader. For example, the code would output the single line from the text file and then you would type what it says and then it would output the next line and so on.
My code so far:
public class JavaApplication6 {
public static String scannedrap;
public static String scannedrapper;
public static void main(String[] args) throws FileNotFoundException, IOException {
File Tunes;
Tunes = new File("E:\\NEA/90sTunes.txt");
System.out.println("Ready? Y/N");
Scanner SnD;
SnD = new Scanner(System.in);
String QnA = SnD.nextLine();
if (QnA.equals("y") || QnA.equals("Y")) {
System.out.println("ok, starting game...\n");
try {
File f = new File("E:\\NEA/90sTunes.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
}
}
}
}
It outputs:
Ready? Y/N
y
ok, starting game...
(and then the whole text file)
But I wish to achieve something like this:
Ready? Y/N
y
ok, starting game...
(first line of file outputted)
please enter (the line outputted)
& then repeat this, going through every line in the text file until it reaches the end of the text file (where it would output something like "game complete")...
This would read the first line ".get(0)".
String line0 = Files.readAllLines(Paths.get("enter_file_name.txt")).get(0);
This block of code reads the whole file line by line, without stopping to ask for user input:
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
Consider adding a statement to the loop body that seeks some input from the user, like you did above when asking if they were ready ( you only need to add one line of code to the loop, like the line that assigns a value to QnA )

Split comma separated values in java, int and String

I have the following in a text file to import into an ArrayList:
Australia,2
Ghana,4
China,3
Spain,1
My ArrayList is made up of objects from another class, Team which has the fields TeamName and ranking. I can get the following to import the String and int into the team name, but I can't separate the number which is supposed to be the teams ranking:
public void fileReader()
{
try
{
String filename = "teams.txt";
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
for (Team teams : teams)
{
teams.setTeamName(parser.next());
teams.setRanking(parser.next()); //this doesn't work
}
}
catch (IOException e)
{
System.out.println("Cannot find file");
}
}
I'm guessing I have to use a split somewhere along the line, or convert a String to an integer??
Check out opencsv. It's 2018 and you shouldn't have to parse a text file yourself :).
By default scanner will use white space as delimiter
Override this by calling useDelimiter method in your case parser.useDelimiter(',');
Then for converting ranking string to int you parser.nextInt()
You can code something like below to suite your purpose.
You have two tokens in your use case i.e. comma (,) and new line (\n). As a result, next() can't be used in a straight forward way.
I am going over each line, then tokenizing each line on comma and finally getting subsequent tokens.
try
{
String filename = "teams.txt";
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
for (Team teams : teams)
{
String[] splitLine = sc.nextLine().split(","); // comma delimited array
teams.setTeamName(splitLine[0]);
teams.setRanking(splitLine[1]);
}
}
Scanner.next() read the next token from input stream, and give String.
If you want to read the next integer, you should use nextInt() instead:
teams.setRanking(parser.nextInt());
Edit
You got InputMismatchException because by default, Scanner use java whitespace as delimeter.
WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+")
In your case, the delimeter are comma , and new line \n so you should config the delimeter for your scanner:
Scanner parser = new Scanner(inputFile);
s.useDelimiter(",|\\n")
Another work around is to read the whole line and parse your line:
String line = parse.nextLine();
String[] parts = line.split(",");
team.setTeamName(parts[0]);
team.setRanking(Integer.parse(parts[1]));
You can choose one of the two solutions above

Java - How to read a big file word by word instead of line by line?

I'd like to read the "text8" corpus in Java and reformat some words. The problem is, in this 100MB corpus all words are on one line. So if I try to load it with BufferedReader and readLine, it takes away too much space at once and can't handle it to separate all the words in one list/array.
So my question: Is it possible in Java to read instead of line by line a corpus, to read it word by word? So for example because all words are on one line, to read for example 100 words per iteration?
you can try using Scanner and set the delimiter to whatever suits you:
Scanner input=new Scanner(myFile);
input.useDelimiter(" +"); //delimitor is one or more spaces
while(input.hasNext()){
System.out.println(input.next());
}
I would suggest you to use the "Character stream" with FileReader
Here is the example code from http://www.tutorialspoint.com/java/java_files_io.htm
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
It reads 16 bit Unicode characters. This way it doesnt matter if your text is in one whole line.
Since you're trying to search word by word, you can easy read till you stumble upon a space and there's your word.
Use the next method of java.util.Scanner
The next method finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of Scanner.hasNext returned true.
Example:
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String a = sc.next();
String b = sc.next();
System.out.println("First Word: "+a);
System.out.println("Second Word: "+b);
sc.close();
}
Input :
Hello Stackoverflow
Output :
First Word: Hello
Second Word: Stackoverflow
In your case use Scanner for reading the file and then use scannerobject.next() method for reading each token(word)
try(FileInputStream fis = new FileInputStream("Example.docx")) {
ZipSecureFile.setMinInflateRatio(0.009);
XWPFDocument file = new XWPFDocument(OPCPackage.open(fis));
ext = new XWPFWordExtractor(file);
Scanner scanner = new Scanner(ext.getText());
while(scanner.hasNextLine()) {
String[] value = scanner.nextLine().split(" ");
for(String v:value) {
System.out.println(v);
}
}
}catch(Exception e) {
System.out.println(e);
}

Finding and replacing words in a text file with Scanner and Printwriter classes

I'm currently attempting to write a program that can scan a text document and replace a specified word / string / whatever with another phrase, specifically using the classes Scanner and Printwriter. Unfortunately, I'm having a little bit of trouble finding the correct methods to use and how exactly to implement them. Here's my code:
class Redaction {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the filename of the sensitive information");
String f = input.next();
System.out.println("Please input what text you want 'lost'");
String o = input.next();
System.out
.println("Please input what you want the new, improved filename to be called");
String n = input.next();
File sensitiveDocument = new File(f);
if (!sensitiveDocument.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}
Scanner in = new Scanner(sensitiveDocument);
in.useDelimiter("[^A-Za-z]+");
PrintWriter out = new PrintWriter(n);
while (in.hasNext()) {
if (in.hasNext(o)) {
// ...
}
}
in.close();
out.close();
}
}
I'm pretty lost at this point. Any help would be much appreciated.
Start by reading PrintWriter and Scanner documentation, to decide which methods to use.
Pseodo code:
Get line by line (or word by word, depends on what you want to remove).
look for the string you want to remove
if the string contains the content to remove, remove it.
print the string to the file.
The simplest although not so efficient algorithm would be to read the contents of the file into a string variable. After which you could use a String Tokenizer to find and replace the word you don't want with the word you want and rewriting the contents of the variable back into the file.

Regarding scanner class

I am currently using StringTokennizer class to split a String into different token as by defined delimiter..
public class App {
public static void main(String[] args) {
String str = "This is String , split by StringTokenizer, created by Neera";
StringTokenizer st = new StringTokenizer(str);
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
}
}
My query is that can same thing can also be achieved through scanner class also ...!! Is it the right approach to use the scanner class since I was reading The Scanner class allows you to tokenize data from within a loop, which allows you to stop whenever you want to... I have tried the following thing, but it doesn't work ...please advise me ..!!!
public class App1 {
public static void main(String[] args)
{
Scanner scanner = new Scanner("This is String , split by StringTokenizer, created by Neera").useDelimiter(", ");
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
}
Use scanner.next() to return the next token instead of scanner.nextLine(), which returns the next full line (and your input only has one). And of course you'll want to use hasNext() in your while instead of hasNextLine().
In response to your comment:
Your code has a syntax mistake, which I originally took for a typo and corrected in the question. You're writing:
while (scanner.hasNext()) ;
System.out.println(scanner.next());
Which properly formatted should tell you what's really happening:
while (scanner.hasNext())
; // empty statement
System.out.println(scanner.next());
It should be:
while (scanner.hasNext()) {
System.out.println(scanner.next());
}

Categories

Resources