I am taking a command line input string like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
I want to split this string which is:
String line = "int t; //variable t
t->a = 0; //t->a does something
return 0;"
like this:
String[] arr = line.split("\n");
arr[0] = "int t; //variable t";
arr[1] = "t->a=0; //t->a does something";
arr[2] = "return 0";
but when i run my java program that split function only returns this:
arr[0] = "int t; //variable t";
it didn't returns other two strings that i mentioned above,why this is happening please explain.
The method readLine() will read the input until a new-line character is entered. That new-line character is "\n". Therefore, it won't ever read the String separated by "\n".
One solution:
You can read the lines with a while loop and store them in an ArrayList:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
for (String s : lines) {
System.out.println(s);
}
To stop the while you will have to press Ctrl + z (or Ctrl + d in UNIX, if I'm not wrong).
From your comment you seem to take the input like this
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
Here the line represents already split string by \n. When you hit enter on the console, the text entered in one line gets captured into line. As per me you are reading line, only once which captures just int t;//variable t, where there is nothing to split.
This should work!Also make sure if your input contains \n
String[] arr = line.split("\r?\n")
Related
Lets assume I have a txt file called "Keys.txt":
Keys.txt:
Test 1
Test1 2
Test3 3
I want to split the strings into an array and I dont know how to do it
I want that the result will be
in array like this:
Test
1
Test1
2
Test2
3
I have this started code:
FileReader fr = new FileReader("Keys.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
br.close();
System.out.println(str);
You could store all the lines on a single string, separated by spaces, and then split it into your desired array.
FileReader fr = new FileReader("Keys.txt");
BufferedReader br = new BufferedReader(fr);
String str="", l="";
while((l=br.readLine())!=null) { //read lines until EOF
str += " " + l;
}
br.close();
System.out.println(str); // str would be like " Text 1 Text 2 Text 3"
String[] array = str.trim().split(" "); //splits by whitespace, omiting
// the first one (trimming it) to not have an empty string member
You can follow these steps :
read the current line in a String, then split the String on the whitespace (one or more) and you have an array which you can store elements in a List.
repeat the operation for each line.
convert the List to an array(List.toArray()).
For example :
List<String> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("Keys.txt"))) {
String str;
while ((str = br.readLine()) != null) {
String[] token = str.split("\\s+");
list.add(token[0]);
list.add(token[1]);
}
}
String[] array = list.toArray(new String[list.size()]);
Note that by using Java 8 streams and the java.nio API (available from Java 7) you could be more concise :
String[] array = Files.lines(Paths.get("Keys.txt"))
.flatMap(s -> Arrays.stream(s.split("\\s+"))
.collect(Collectors.toList())
.stream())
.toArray(s -> new String[s]);
String str = "Test 1 Test1 2 Test2 3";
String[] splited = str.split("\\s+");
You can use String.split() method (in your case it's str.split("\\s+");).
It will split input string on one or more whitespace characters. As Java API documentation states here:
\s - A whitespace character: [ \t\n\x0B\f\r]
X+ - X, one or more times.
FileReader fr;
String temp = null;
List<String> wordsList = new ArrayList<>();
try {
fr = new FileReader("D://Keys.txt");
BufferedReader br = new BufferedReader(fr);
while ((temp = br.readLine()) != null) {
String[] words = temp.split("\\s+");
for (int i = 0; i < words.length; i++) {
wordsList.add(words[i]);
System.out.println(words[i]);
}
}
String[] words = wordsList.toArray(new String[wordsList.size()]);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
try this out
the following code will only read the first line of a text file and it will stop there. I've been experimenting with loops but i cannot get it to successfully update the line until there are no more lines in the file. can anyone help? thanks
public void readFile(){
try {
BufferedReader in = new BufferedReader(new FileReader("test1.txt"));
words = new ArrayList<Word>();
int lineNum = 1; // we read first line in start
// delimeters of line in this example only "space"
char [] parse = {' '};
String delims = new String(parse);
String line = in.readLine();
String [] lineWords = line.split(delims);
// split the words and create word object
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
line = in.readLine();
in.close();
} catch (IOException e) {
}
}
Basically, you want to keep reading until you run out of lines, at which time BufferedReader will return null
char[] parse = {' '};
String delims = new String(parse);
String line = null;
while ((line = in.readLine()) != null) {
String[] lineWords = line.split(delims);
// split the words and create word object
for (int i = 0; i < lineWords.length; i++) {
Word w = new Word(lineWords[i]);
words.add(w);
}
lineNum++; // pass the next line
}
You should be managing your resources better, if you open it, you should make all reasonable attempts to close. Currently, if your code fails for some reason, the in.close line will never be called. Also, you shouldn't ignore exceptions
Luckily, in Java 8, this is easy to manage...
try (BufferedReader in = new BufferedReader(new FileReader("test1.txt"))) {
//...
} catch (IOException e) {
e.printStackTrace();
}
Take a closer look at Basic I/O, The try-with-resources Statement and BufferedReader JavaDocs, especially BufferedReader#readLine
You may also want to take a look at LineNumberReader ;)
while((line = in.readLine()) != null){
//process line
}
This nested statement reads a line from the BufferedReader and stores it in line. At the end of the file, readLine() will return null and stop the loop.
I am trying to loop through a text file, and according to my logic it is supposed to loop though while, line is not null, and then in another while loop inside of that loop, its supposed to loop through the line while a variable does not equal one of my command line arguments and then its supposed to take the first token of the line and add it to that variable. But every time I run the code I get no such element exception, i don't understand why?
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
String id = new String();
StringTokenizer st = new StringTokenizer(line, ",");
while(line != null){
while(!id.equals(args[0])){
line = br.readLine();
id = st.nextToken();
}
}
} catch (FileNotFoundException e) {
System.out.println("file not found");
} catch (IOException e) {
System.out.println("not a string");
}
The file looks something like this:
line1: 118, s, m, p
line2: 111, s, m, c
nextToken()
NoSuchElementException--This is thrown if there are no more tokens in
this tokenizer's string
At this code
while(!id.equals(args[0])){
id = st.nextToken();
}
Your loop will continue until your while condition(while(!id.equals(args[0]))) fails. So check your args[0] with id by printing them on console before your while condition.
Modify your code a little bit
String line ="";
String id = new String();
while((line = br.readLine())!= null){
StringTokenizer st = new StringTokenizer(line, ",");
while(!id.equals(args[0])){
id = st.nextToken();
}
}
Your file contains 118, s, m, p .. a space after , so I guess your tockenizer string should be ", "
I have files containing text in pattern like this
Type:status
Origin:some text
Text:some text
URL:some url
Time:time
around 500 lines with same pattern. I want to extract only the text part from it. I tried reading the file with BufferedReader and used indexOf("Text") and indexOf("URL") and subString(i,j) but its giving exception at run time. How can I do this. My code:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
str= str + s;
i = str.indexOf("Text:");
j= str.indexOf("URL:");
String a= str.substring(i, j);
bw.write(a);
}
br.close();
bw.close();
The "Text:" is found first in the 3rd line and "URL:" in the 4th, but if your program doesn't find both strings, it throws an exception.
Even if it worked you would find the same text over and over again.
Try something like this:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
String s;
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
if (s.startsWith("Text:"))
bw.write(s);
}
br.close();
bw.close();
You could use
String[] pieces = str.split(":");
That will give you an array of strings split by what ever you put in the parenthesis. Then if you know the pattern you can get each piece out by iterating through it in a loop. For example: if you know that Type is at [0] and six things in each sequence you can say that the next Type will be at [6] and so on.
You should check for indexes. Of i and j. If one line is wrong, it will skip it and print the line that is wrong to the console. You should probably handle it in a different way but keep in mind that substring shouldn't love indexes of -1.
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String tokenText = "Text:";
String tokenURL = "URL:";
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
String a;
str = str + s;
i = str.indexOf(tokenText);
j = str.indexOf(tokenURL);
if (i < 0 && j >= 0){
// pad with the token string
a = s.substring(j + tokenURL.length);
} else if(i >= 0) {
// pad with the token string
a = s.substring(i + tokenText.length);
} else {
System.out.printl("Unparsed line:");
System.out.printl(s);
}
bw.write(a);
}
br.close();
bw.close();
That said, as jonhchen902 said in the comments, you could also check for the strings after the while loop. It really depends on your input file and if you're expecting to find the "string" multiple times or once.
According to your example, Text: and Url: are on consecutive lines.
Your problem is you're reading the file line by line (br.readLine()), so calling indexOf() will most of the time return -1 in i or j (and you will never find both strings, since they aren't on the same line).
As the javadoc of substring() states, calling the method with a negative start index will throw an IndexOutOfBoundsException. So your approach isn't right.
You should instead parse the file line by line as you're doing, and simply test for a positive index to the call to indexOf("Text:"), and then substring the current line starting at the returned index + 5.
Not tested:
while ((line = br.readLine()) != null) {
i = line.indexOf("Text:");
if (i > 0) {
String text = line.substring(i);
bw.write(text + "\n");
}
}
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);