Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am developing a program that takes input from the console. So far it has been no problem reading input that consists of one line of input from the console. But the program does not work when it is supposed to read multiple lines. How can i improve the readInput method to read multiple lines of input and the return a single String containing all of the input from different lines.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
String input = inputstream.readLine();
return input;
}
So when you write String input = inputstream.readLine() This reads one line at a time,
As you are taking input from the user there would not be any null cases even if the user clicks enter, You need to check for the length of the input string, If it is 0 then break from the while loop.
But this isn't the case when you are reading from a file or other source you need to check whether the input is null or not.
Hope this could help you.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
StringBuilder finalString = new StringBuilder();
String input = inputstream.readLine();
while(true){
finalString.append(input);
input=inputstream.readLine();
if(input.length() == 0){
break;
}
}
br.close();
return finalString;
}
Input:
hi hello
how are you
Am fine
Output:
hi hellohow are youAm fine
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am working on the password login portion of a class project. Nothing fancy. User, or role will be an int and password is a String. I am just using a simple encryption for now. The problem I am having is while reading the file I am getting an input mismatch. I have done something similar in the past that required me to read ints and Strings and did not have any problems. But I just cannot figure out what is going wrong in this case. Any help as to why I am getting this error would be greatly appreciated. I am using while(inputStream.hasNextLine()) then read the int and then the String I have tried hasNextInt and hasNext and keep getting the same error.
public void readFile(){
Scanner inputStream = null;
try {
inputStream = new Scanner (new FileInputStream("login.txt"));
}catch (FileNotFoundException e) {
e.printStackTrace();
}
if(inputStream != null){
while (inputStream.hasNextLine()){
int luser = inputStream.nextInt();
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
count ++;
}
inputStream.close();
}
}
Try reading it as a String and converting the string to an int
while (inputStream.hasNextLine()) {
Integer luser = Integer.parseInt(inputStream.nextLine());
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
count++;
}
But you need to make sure your file has your data in the exact format as below
12342
password
It's hard to say without knowing what error it is that you are getting, but my guess is that it is because you are not reading the entire file.
Your file probably looks like this:
1\r\n
password\r\n
When you call nextInt() it reads the int, but doesn't advance past the first \r\n so when you call nextLine() it reads to the end of the line so all you get is \r\n. You need to read past the first \r\n and then read the password.
Try
int luser = inputStream.nextInt();
inputStream.nextLine();
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
is there any simple way (in Java 7) to:
open in reading mode a file containing, for every line, a path to another file
for every line/path, open the respective file and print the content
(Every file is a plain text file)
?
Sorry if the question is silly.
Thank you
try something like this:
public static void main(String[] args) throws IOException {
// open stream to path list file
InputStream indexSource = new FileInputStream("index.txt");
// create reader to read content
try(BufferedReader stream = new BufferedReader(new InputStreamReader(indexSource))) {
// loop
while (true) {
// read line
String line = stream.readLine();
if (line == null) {
// stream reached end, escape the loop
break;
}
// use `line`
printFile(line);
}
}
}
static void printFile(String path) throws IOException {
// open stream to text file
InputStream textSource = new FileInputStream(path);
// print file path
System.out.println("### " + path + " ###");
// create reader to read content
try(BufferedReader stream = new BufferedReader(new InputStreamReader(textSource))) {
// loop
while (true) {
// read line
String line = stream.readLine();
if (line == null) {
// stream reached end, escape the loop
break;
}
// print current line
System.out.println(line);
}
}
// nicer formatting
System.out.println();
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am experiencing very strange behavior with BufferedReader. I want to read an entire file however it only reads every other line.
E.g the file below
1 //ignore the left most space - shouldn't exist
2
3
4
5
6
Will output
2
4
6
Here is some of my code...
fileRead = new BufferedReader(new InputStreamReader( new FileInputStream(file)));
public void scan(){
if (fileRead != null){
try{
while ((fileRead.readLine()) != null){
String line = fileRead.readLine();
String abcLine = line;
System.out.println(line);
}
}catch(IOException e) {
System.out.println("Line can not be read");
}
}else{ System.out.println("Can not Read - File Not Found"); }
}
My best bet is the bug lies within the while statement. Is this the correct way to ensure
you read the file until you reach EOF "end of file" ?
Any insight is truly appreciated
Thank you!
You're reading two lines each time through the loop. Your current code is:
while ((fileRead.readLine()) != null){ // reads a line, ignores it
String line = fileRead.readLine(); // reads another line, stores in 'line'
... // do stuff with 'line'
}
Every call to readLine() reads a line. You probably want something more like:
String line;
while ((line = fileRead.readLine()) != null) {
... // do stuff with 'line'
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a minor problem that sets me back nearly all day and I would like some input on how to solve it.
I am making a servlet for my site and I have a formatted .txt in the following form:
Name,Surname,Age
for example:
mary,jane,23
mark,thomson,25
.
.
.
etc
I want somehow to read this txt in order to pass these strings from my .txt to my database, in the corresponding fields.
Thanks in advance for any input!
Maybe this will get you started:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null) {
String [] split = line.split(",");
String name= split[0];
String surname= split[1];
Integer age= Integer.parseInt(split[2]);
//save it to the database
}
//close the reader somewhere
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
Arraylist<String> string_array = new Arraylist<String>();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
string_array.add(sb.soString());
}
} finally {
br.close();
}
Subsequently you will separate by comma every element/line in your String Arraylist
string_array[i].split(',');
and you will proceed to any action you want with the data.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Say I did a calculation:
1000 * 2000
How would I print the results of that calculation to a .txt file?
You can use the PrintWriter class. Something like:
PrintWriter w = new PrintWriter("filename.txt", "UTF-8");
w.println(calculation);
This will create a new file with the specified name, or it will overwrite one if it already exists.
I think your have trouble with variable types. Convert the Int to String. I haven't tried the code.
Integer.toString(1000 * 2000);
public static void saveAs() throws IOException {
System.out.println("Type In The New File Name"); //FILE NAME CHOICE
Scanner fileChoice = new Scanner(System.in); //this scans userinput
String newFile; //this is userinput
newFile = fileChoice.nextLine(); //whatever they type is stored in this var
File fileWriter = new File(newFile); //opens a new file
PrintWriter writeNew = new PrintWriter(new FileWriter(newFile, true)); //writes to it
writeNew.println("TEXT HERE BLAH") //writes the text to that file
writeNew.close(); //and dont forget to close
when the userinput will ask you for file name SPECIFY IT IS .TXT eg. type in hello.txt
problemsolved-