Stdin reading multiple lines - java

I have the following code:
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String submittedString = "";
System.out.flush();
submittedString = stdin.readLine();
int numberofLines = Integer.parseInt(submittedString.split(" ")[0]);
for(int i = 0; i < numberofLines; i++)
submittedString += stdin.readLine();
zipfpuzzle mySolver = new zipfpuzzle();
mySolver.getTopSongs(submittedString);
However, despite the input being over multiple lines, this only reads the first.
Where is my mistake?
If it makes any difference, I am compiling on eclipse.
Cheers!
Dario

Just use an array and populate it within your for-loop:
String[] inputs = new String[numberofLines];
for (int i = 0; i < numberofLines; i++)
inputs[i] = stdin.readLine();
Extra Note:
If you want multiple lines with single String:
String submittedString = "";
for (int i = 0; i < numberofLines; i++)
submittedString += stdin.readLine() + System.getProperty("line.separator");

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while ((line = stdin.readLine()) != null){
// Do something.
submittedString += line + '\n';
}

submittedString = stdin.readLine();
BufferedReaders readLine method will read System.in until it hits a new line, therefore if you're using the first line of the file to determine the number of lines to read then your data must be incorrect.

Related

Array/Loop does not output primary line

I'm having a small problem with my code and I'm not exactly sure how to fix it.. Basically I'm trying to separate the file into different lines (Frames) and then input those lines into the file, and proceed to print them. My first line of the file never prints.
public class Main {
public static void main(String[] args) throws IOException
{
/*Switch switcherino = new Switch();*/
Frame frame = new Frame();
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to process: ");
String fileName = input.nextLine();
FileInputStream inputStream =
new FileInputStream(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream,Charset.forName("UTF-8"));
BufferedReader bufferedReader =
new BufferedReader(inputStreamReader);
try{
String str = " ";
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
}
catch (IOException e){
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
I don't want to use an ArrayList, as much as it would probably be easier.
Thanks in advance!
File: (switch.txt)
fa00 123123123abc 111111222222 data1
fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5
Output: (from System.println(words[i]);)
fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5
This is wrong logic: you read the line, you split it into words so then go ahead and print them - no need to try and read any more lines
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
use this instead
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
System.out.println(words[i]);
}
}
// to count length
int length = 0;
BufferedReader br =
new BufferedReader(inputStreamReader);
while(true){
str = br.readLine();
if(str == null) break;
else length++;
} // this loop counts the length!!
final int clength = length;
//now this is what you want!
String words[] = new String[clength];
int j= 0;
while(true){
str = bufferedReader.readLine();
if(str == null) break;
words[j++] = str;
System.out.println(str); //FIXED
}
//Now the words[] have all the lines individually
Your code doesn't work because you called readLine() twice, which skipped the first line. Try this and let me know.
You don't need to use split() since you want the entire line :)
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
When iterate the file, you split your first line into a String array,
words[] contains the following elements : fa00, 123123123abc, 111111222222 and data1.
and then the inner for loop iterate your bufferReader and you assign the lines to a specific index of word and then you print out the word array elements
You are not supposed to invoke bufferedReader.readLine() in the inner for loop, it breaks your logic.

Split a text file into blocks

I need to read a text file, and break the text into blocks of 6 characters (including spaces), pad zeroes to the end of text to meet the requirement.
I tried doing it and here is what I have done.
File file = new File("Sample.txt");
String line;
try {
Scanner sc = new Scanner(file);
while(sc.hasNext()){
line = sc.next();
int chunk = line.length();
int block_size=6;
if((chunk%block_size) != 0)
{
StringBuilder sb = new StringBuilder(line);
int val = chunk%block_size;
for(int i=0; i<val; i++){
sb.append(" ");
}
line = new String(sb.toString());
}
int group = line.length() / block_size;
String[] b = new String[group];
System.out.println(line);
System.out.println(chunk);
int j =0;
for(int i=0; i<group;i++){
b[i] = line.substring(j,j+block_size);
j += block_size;
}
System.out.println("String after spliting is: ");
for(int i=0; i<group;i++){
System.out.println(b[i]);
}
}
}
Now this works fine when the text in the input file has no spaces between words. But when I add spaces gives me a different output. I am stuck up at this point. Any suggestions on the same ?
I don't want to write the solution for you, but I'd advise you that what you're trying to accomplish might be easier to do using a BufferedReader with a FileReader and by using Reader.read(buf) where buf is a char[6];

java 2D array from text file

I am trying to make this input.txt into a 2D array. I tried a few different methods. This is my latest attempt, and I seem to be stuck here... Any help is much appreciated.
input.txt structure: SCI2000/Science/1200/10/C --> There are 23 rows and 5 columns. I'd also like to have a title made for each column.
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
String[][] input = new String[23][5];
String[] tokens = everything.split("/");
for(String str : tokens)
System.out.print(str);
Just the main processing part (not tested):
int columns = 5;
String[] row = String[columns];
int j = 0;
while ((line = br.readline) != null) {
row = line.split("/");
for(int i=0; i<row.length; ++i) {
input[j,i] = row(i);
}
++j;
}
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
String[][] input = new String[24][5]; // 1 row for title, 23 rows for data
// add title
input[0] = new String[]{"title1", "title1", "title1", "title1", "title1"};
String line = br.readLine();
int row = 1; // update here
while ( (line = br.readLine())!= null ) {
input[row++] = line.split("/");
}
// print all data
for ( int i = 0; i < input.length; i++) {
for ( int j = 0; j < input[i].length; j++ )
System.out.print(input[i][j] + " ");
//new line
System.out.println();
}

How to read from a specific line of a file

I have a text file (called data.txt, which has 350 lines)
How can I find the text on a given line of the file? For example:
int imageVariable = 5;
String imageText = nthLineOfFile(imageVariable);
textView1.setText(imageText);
I'm trying to write the String nthLineOfFile(int image) function.
Thanks
You may try this:
String str = FileUtils.readLines(file).get(lineNumber);
or you may use the conventional way by using BufferedReader class:
BufferedReader r = new BufferedReader(new FileReader(file));
for (int i = 0; i < lineNumber - 1; i++)
{
r.readLine();
}
return r.readLine();
You can use Scanner:
Scanner fileIn = new Scanner(your file);
for (int i = 0; i < lineNum - 1; i++) {
fileIn.nextLine(); // ignore
}
nthLine = fileIn.nextLine();

Number of newline characters

I am designing a Utility that counts the words and Number of newline characters.
I have done count task but i dont know how to count number of new line charcaters in file.
Code:
System.out.println ("Counting Words");
InputStream stream = Run.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
BufferedReader br = new BufferedReader (r);
String line = br.readLine();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts){
count++;
}
line = br.readLine();
}
System.out.println(count);
test
This is simple file reading by Java Program
Just look inside the words:
for (char c : w.toCharArray()) {
if (c == '\n') {
numNewLineChars++;
}
}
Which goes inside the for loop you already have.
System.out.println ("Counting Words");
InputStream stream = Run.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
BufferedReader br = new BufferedReader (r);
String line = br.readLine();
int word_count = 0;
int line_count = 0;
while (line != null) {
String[] parts = line.split(" ");
word_count += parts.length;
line_count++;
line = br.readLine();
}
System.out.println("Word count: " + word_count + " Line count: " + line_count);
It maybe a better option here to use the LineNumberReader class for counting and reading the lines of text. Although this isn't the most efficient way for counting lines in a file (according to this question) it should suffice for most applications.
From LineNumberReader for readLine method:
Read a line of text. Whenever a line terminator is read the current line number is incremented. (A line terminator is usually a newline character '\n' or a carriage return '\r').
This means that when you call the getLineNumber method of the LineNumberReader class, it will return the current line number that has been incremented by the readLine method.
I have included comments in the code below explaining it.
System.out.println ("Counting ...");
InputStream stream = ParseTextFile.class.getResourceAsStream("/test.txt");
InputStreamReader r = new InputStreamReader(stream);
/*
* using a LineNumberReader allows you to get the current
* line number once the end of the file has been reached,
* without having to increment your original 'count' variable.
*/
LineNumberReader br = new LineNumberReader(r);
String line = br.readLine();
// use a long in case you use a large text file
long wordCount = 0;
while (line != null) {
String[] parts = line.split(" ");
wordCount+= parts.length;
line = br.readLine();
}
/* get the current line number; will be the last line
* due to the above loop going to the end of the file.
*/
int lineCount = br.getLineNumber();
System.out.println("words: " + wordCount + " lines: " + lineCount);

Categories

Resources