I need to read a text file and split using a common text in the lines, and print a part of the split text. This works fine but only does this for the first line in the text.
However, if I print lines without the split part, it prints correctly. Please what am I doing wrong?
File sample: (I want to split by "words")
Line 1 This text is of length: 7 words. I need to learn how to program.
Line 2 Now we have text of length: 3 words. No matter what the words are, I must program
FileInputStream fis = new FileInputStream(fin);
//Construct BufferedReader from InputStreamReader
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
ArrayList<String> txt1 = new ArrayList<>();
while ((line = br.readLine()) != null) {
String[] pair = line.split("words");
txt1.add(pair[1]);
System.out.println(txt1);
//System.out.println(line);
}
br.close();
Given the following unit test simulating the input of a file via a StringInputStream:
#Test
public void test() throws IOException
{
String fileContent = "This text is of length: 7 words.\r\nI need to learn how to program and one day.";
StringInputStream stream = new StringInputStream(fileContent);
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = null;
ArrayList<String> txt1 = new ArrayList<>();
while ((line = br.readLine()) != null) {
String[] pair = line.split("words");
txt1.add(pair[1]);
System.out.println(txt1);
//System.out.println(line);
}
}
The first line will be split into
"This text is of length: 7 " and
"."
Since you put item [1] into the array list, it'll just contain a single dot.
The second line will be split into
"I need to learn how to program and one day."
only. There is no second item, so accessing [1] results in a ArrayIndexOutOfBoundsException.
Related
I want to be able to read an entire text file that has empty lines between text. Every solution I try to implement seems to stop reading after it reaches an empty line. I want to be able to read an entire text file, including empty lines, and store the contents in a String. This is what I have now. I included two implementations. How can I alter either of the implementations to continue reading after an empty line? Also, I want the empty lines in the text file to be included in the String that it is being stored in.
File templateFile = new File(templatePath);
String oldContent = "";
BufferedReader reader = new BufferedReader(new FileReader(templateFile));
//Implementation 1
String line = reader.readLine();
while(line != null) {
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
/* Implementation 2
Scanner sc = new Scanner(templateFile);
while(sc.hasNext()) {
oldContent = sc.nextLine();
} */
Using java 11 java.nio.file.Files.readString()
oldContent = Files.readString(Paths.get(templatePath));
I have the following code
InputStream inputStream = sock.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine()) != null) {
String[] data = line.split("\\s+");
//rest of the code
The sender is supposed to send the following String
String DataToSend = "Name John City NewYork \t\t"
What I want is confirm the message coming from client to server ends with double tab \t\t, it doesn't show in the String[] data.
First of all, you need to understand these 2 things:
reader.readLine() will give you string without the newline,
because it reads until newline.
line.split("\\s+") will give you string(s) without whitespace characters, because it splits based on the whitespace characters.
\t, \n, \r, space, are all whitespace characters.
Now, depends on what you want, there are few things that you can do:
check \t\t at the end of each line
You can check before splitting the strings, sample code:
InputStream inputStream = new ByteArrayInputStream("hello\t\t".getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.endsWith("\t\t")) { // check if it ends with \t\t
// do something
}
String[] data = line.split("\\s+");
}
Note: when the \t\t is in the middle of the string e.g. hello\t\tworld, it will not be handled.
read strings until \t\t
You can use Scanner and set \t\t as the delimiter, sample code:
InputStream inputStream = new ByteArrayInputStream("hello\t\tworld\nit's me".getBytes());
Scanner scanner = new Scanner(inputStream);
scanner.useDelimiter("\t\t");
int count = 1;
while (scanner.hasNext()) {
String data = scanner.next();
System.out.println("data number " + count + ":");
System.out.println(data);
System.out.println();
count++;
}
Output:
data number 1:
hello
data number 2:
world
it's me
I am trying to read parts of a text file with the format
John Smith
72
160
The first line being the name (string), and the second and third lines being height and weight (both ints). However, I cannot find a way to store each of these into their own variables, instead I can only figure out how to store the whole thing into one variable and print it. This is the code that I have as of now
try
{
File file = new File("person.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println(stringBuffer);
}
In this part
stringBuffer.append(line);
stringBuffer.append("\n");
I was thinking of trying to add a part in the middle of both those lines that stored a variable, but it did not seem possible. I also thought of using a for loop and using that to my advantage somehow, but could not figure out a way to do it with that either.
Is there any possible way to do this that I do not know about? Thank you
Reading and parsing a text file in Java has been getting easier in every new version. You can try the following way:
List<String> lines = Files.lines(Paths.get("person.txt")).collect(Collectors.toList());
String name = lines.get(0);
Integer height = Integer.parseInt(lines.get(1));
Integer weight = Integer.parseInt(lines.get(2));
File file = new File("person.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String firstline = bufferedReader.readLine();
String secondline = bufferedReader.readLine();
String thirdline = bufferedReader.readLine();
fileReader.close();
i am writing a java program to read a file and print output to another string variable.which is working perfectly as intended using is code.
{
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
}
System.out.println(key); //this prints contents of .txt file
}
this prints whole text in the file.But i want to only print the lines till word END is encountered in file.
example: if input.txt file contains following text : this test file END extra in
it should print only :
this test file
Just do a simple indexOf to see where it is and if it exists in the line. If the instance is found one option would be using substring to cut off everything up until the index of the keyword. For a bit more control though try using java regular expressions.
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while ((line = reader.readLine()) != null && line.indexOf("Keyword to look for") == -1)
key += line;
System.out.println(key);
I am not sure why it needs to be any more complicated than this:
BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = re.readLine();
if (str.equals("exit")) break;
// whatever other code.
}
You can do it in many ways. one of them is using indexOf method to specify the start index of "END" in input and then using subString method.
for more information, read documentation of String calss. HERE
This will work for your issue.
public static void main(String[] args) throws IOException {
String key = "";
FileReader file = new FileReader("/home/halil/khalil.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
} String output = "";
if(key.contains("END")) {
output = key.split("END")[0];
System.out.println(output);
}
}
You have to change your logic to check if the line contains "END".
If END not found in a line, add the line to key stringin your program
If yes, split that line into word array, read the line till you encounter the word "END" and append it to your key string. Consider using Stringbuilder for key.
while (line != null) {
line = reader.readLine();
if(!line.contains("END")){
key += line;
}else{
//Note that you can use split logic like below, or use java substring
String[] words = line.split("");
for(String s : words){
if(s.equals("END")){
return key;
}
key += s;
}
}
}
I have been trying to get a specific columns from a csv file say having 30 columns but i need only 3 columns entirely when i execute the following code only i get only one entire column data..how to get 3 column data at a time.when i run it prints only one column...when i try to print multiple column it shows error message like
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ReadCVS.main(ReadCVS.java:19)
public static void main(String[] args) throws Exception {
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("txt.csv"));
String line = br.readLine();
while((line = br.readLine()) !=null){
String[] b = line.split(splitBy);
PrintWriter out = new PrintWriter(new FileWriter("new.csv",true));
out.println(b[0]);
out.close();
}
br.close();
}
The problem is probably is:
You have only one line in your, txt.csv file.
When you called br.readLine(); for the first time, that line is read from the file and stored in String line variable. But you ignored that line, and you've read again, in your while condition:
while((line = br.readLine()) !=null)
So maybe you have an empty line or empty string after that first line. Then the while condition is true, but an empty String is stored in line variable. So the b[] has no element and b[0] is out of the bound.
One solution is to change this line:
String line = br.readLine();
to
String line = null;
[EDIT]
So if you try to read a file like the one in mkyong's site (as you linked in your comment) and split the lines by "," and write them in a new file for example, you can use a code like the code below:
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\new.csv",true));
BufferedReader br = new BufferedReader(new FileReader("c:\\txt.csv"));
String splitBy = ",";
String line = null;
while((line = br.readLine()) !=null){
StringBuffer newLine = new StringBuffer();
String[] b = line.split(splitBy);
for (int i = 0; i<b.length; i++)
{
if(b[i] == null || b[i].trim().isEmpty())
continue;
newLine.append(b[i].trim() + ";");
}
out.write(newLine.toString());
out.newLine();
}
out.close();
br.close();
}
Also you should know that the following line opens the output file in appendable way(the second boolean parameter in the constructor):
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\new.csv",true));
Also I assumed the contents of the source file is the same as in mkyong's site, somethimg like this:
"1.0.0.0",, , ,"1.0.0.255","16777216", , "16777471","AU" ,, "Australia"
"1.0.1.0" , ,, "1.0.3.255" ,, ,"16777472","16778239" , , "CN" , ,"China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
Good Luck.