reading String with spaces java - java

I am trying to read from scanner with spaces, i want to read even the spaces.
for example "john smith" to be read "john smith".
my code is as follow:
when it gets to the space after john it just hangs and doesn't read any more.
any help would be appreciated.
Scanner in = new Scanner(new InputStreamReader(sock.getInputStream()));
String userName = "";
while (in.hasNext()) {
userName.concat(in.next());
}

Scanner.next() returns the next token, delimited by whitespace. If you would like to read the entire line, along with the spaces, use nextLine() instead:
String userName = in.nextLine();

Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
or
private String readFileAsString(String filePath) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}

When we use Scanner.next() to read token there is what we call a delimiter, the default delimiter used in by Scanner is \p{javaWhitespace}+ , you can get it by calling Scanner.delimiter(), which is any char that validate the Character.isWhitespace(char). you can use a customized delimiter for your Scanner using Scanner.useDelimiter().
If you want to take one line as a string so you can use nextLine() , if you already know what is the type of the next token in the input stream, scanner gives you a list of method next*() take convert the token to the specified type. see Scanner's doc here for more info.

Related

How I do make Scanner class reads my complete String input

Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println(str);
Provided input : this is a good school
Obtained Output : this
Why is the complete string is not printing?
Because next() returns the next token, not complete line.
You can use
String str = sc.nextLine();
From the documentation of Scanner.next():
The java.util.Scanner.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.
https://www.tutorialspoint.com/java/util/scanner_next.htm
If you want to read the entire line it is probably better to use this code:
BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
String line=buffer.readLine();
Taken from this answer:
https://stackoverflow.com/a/8560432/481528

Java- toCharArray() method

Scanner in= new Scanner(System.in);
int len=in.nextInt();
String s=in.next();
char[] ch=s.toCharArray();
System.out.println(len);
System.out.println(ch.length);
I have run this code snippet by providing input
400004
//and a string of length 400004
The output was
400004
8190
I know when we use toCharArray() then it returns a char array having same length as of the String. But here it is diffirentcult.
I am not able to understand how this is possile.
Please help me out here.
You most certainly copied and pasted a string that contains a newline character or another character, which made the next method of Scanner return. Thus, only part of the string is copied to s.
I tried this code, only length = 8190 string is entered in String variable because of constraint of command prompt buffer.
You can try getting input from a text file, it works.
See me code billow for reference.
Scanner in = new Scanner(System.in);
int n=0;
String number=null;
BufferedReader br = null;
FileReader fr = null;
try {
br = new BufferedReader(new FileReader("txt file path"));
String len= br.readLine();
n=Integer.parseInt(len);
number = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}

Java Delete Line from File

the code below is from a reference i saw online, so there might be some similarities i'm trying to implement the code to remove an entire line based on the 1st field in this instance it is (aaaa or bbbb) the file which has a delimiter "|", but it is not working. Hope someone can advise me on this. Do i need to split the line first? or my method is wrong?
data in player.dat (e.g)
bbbb|aaaaa|cccc
aaaa|bbbbbb|cccc
Code is below
public class testcode {
public static void main(String[] args)throws IOException
{
File inputFile = new File("players.dat");
File tempFile = new File ("temp.dat");
BufferedReader read = new BufferedReader(new FileReader(inputFile));
BufferedWriter write = new BufferedWriter(new FileWriter(tempFile));
Scanner UserInput = new Scanner(System.in);
System.out.println("Please Enter Username:");
String UserIn = UserInput.nextLine();
String lineToRemove = UserIn;
String currentLine;
while((currentLine = read.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
write.write(currentLine + System.getProperty("line.separator"));
}
write.close();
read.close();
boolean success = tempFile.renameTo(inputFile);
}
}
Your code compares the entire line it reads from the file to the user name the user enters, but you say in your question that you actually only want to compare to the first part up to the first pipe (|). Your code doesn't do that.
What you need to do is read the line from the file, get the part of the string up to the first pipe symbol (split the string) and skip the line based on comparing the first part of the split string to the lineToRemove variable.
To make it easier, you could also add the pipe symbol to the user input and then do this:
string lineToRemove = UserIn + "|";
...
if (trimmedLine.startsWith(lineToRemove)) continue;
This spares you from splitting the string.
I'm currently not sure whether UserInput.nextLine(); returns the newline character or not. To be safe here, you could change the above to:
string lineToRemove = UserIn.trim() + "|";

Java parsing text file and preserving line breaks?

I have been researching how to do this and becoming a bit confused, I have tried so far with Scanner but that does not seem to preserve line breaks and I can't figure out how to make it determine if a line is a line break. I would appreciate if anyone has any advice. I have been using the Scanner class as below but am not sure how to even check if the line is a new line. Thanks
for (String fileName : f.list()) {
fileCount++;
Scanner sc = new Scanner(new File(f, fileName));
int count = 0;
String outputFileText = "";
//System.out.println(fileCount);
String text="";
while (sc.hasNext()) {
String line = sc.nextLine();
}
}
If you're just trying to read the file, I would suggesting using LineNumberReader instead.
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
String line = "";
while(line != null){
line = lnr.readLine();
if(line==null){break;}
/* do stuff */
}
Java's Scanner class already splits it into lines for you, even if the line is an empty String. You just have to scan through the lines again to get your values:
Scanner lineScanner;
while(sc.hasNext())
{
String nextInputLine = sc.nextLine();
lineScanner = new Scanner(nextInputLine);
while(lineScanner.hasNext())
{
//read the values
}
}
You probably want to use BufferedReader#readLine.

Scanner.next() from a BufferedReader

I am trying to scan text from a reader based on a delimiter "()()" by using the Scanner.next() method. Here is my code:
public static void main(String[] args)
{
String buffer = "i want this text()()without this text()()";
InputStream in = new ByteArrayInputStream(buffer.getBytes());
InputStreamReader isr = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(isr);
Scanner scan = new Scanner(reader);
scan.useDelimiter("/(/)/(/)");
String found = scan.next();
System.out.println(found);
}
The problem is, the entire buffer is returned:
i want this text()()without this text()()
I only want the first next() iteration to return:
i want this text
and the next next() iteration to return:
without this text
Any suggestions how I can scan the reader by only delimiting strings ending in ()()?
Your useDelimiter argument is incorrect - you're using forward slashes instead of backslashes when you try to escape the parentheses. You need to escape the backslashes in Java terms, too:
scan.useDelimiter("\\(\\)\\(\\)");
EDIT: Rather than escaping this yourself, you can use Pattern.quote:
String rawDelimiter = "()()";
String escaped = Pattern.quote(rawDelimiter);
scan.useDelimiter(escaped);

Categories