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));
Using Scanner, i'm not sure how to read a file with multiple lines and store it all into a String. I use a loop like :
while(file.hasNext())
{
string += file.nextLine();
}
I find that the file.hasNext method eats up all of the data in the file and so file.nextInt() doesn't have any values to find and so it returns and error. What can I do to "reset" the Scanner? I tried creating a new Scanner object but that didn't change anything. I have to run this string through a method and I have run into this problem many times. What should I do?
Maybe you should try StringBuilder.
StringBuilder builder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
builder.append(line);
// process the line.
}
}
later
String text = builder.toString();
To read the entire contents of a Scanner source into a String, set the Scanner's delimiter to the end of the file:
String contents = file.useDelimiter("\\Z").next();
I have a text file that I need to modify before parsing it. 1) I need to combine lines if leading line ends with "\" and delete white spaced line. this has been done using this code
public List<String> OpenFile() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
StringBuilder concatenatedLine = new StringBuilder();
List<String> formattedStrings = new ArrayList<>();
while ((line = br.readLine()) != null) {
if (line.isEmpty()) {
line = line.trim();
} else if (line.charAt(line.length() - 1) == '\\') {
line = line.substring(0, line.length() - 1);
concatenatedLine.append(line);
} else {
concatenatedLine.append(line);
formattedStrings.add(concatenatedLine.toString());
concatenatedLine.setLength(0);
}
}
return formattedStrings;
}
}
}//The formattedStrings arrayList contains all of the strings formatted for use.
Now My question, how can I search those lines for pattern and assign their token[i] to variables that I can call or use later.
the New combined text will look like this:
Field-1 Field-2 Field-3 Field-4 Field-5 Field-6 Field-7
Now, if the line contains "Field-6" and "Field-2" Then set the following:
String S =token[1] token[3];
String Y =token[5-7];
Question you might have for me, how am I deciding on which token to save to a string? I will manually search for the pattern in the text file and if the "Line contain Field-6 and Field-2 or any other required pattern. Then manually count which token I need to assign to the string. However, it will be nice if there is another way to approach this, for ex assign what's in between token[4] and token[7] to string (s) if the line has token[2] and token[6]. or another way that provides more Granule Control over what to store as string and what to ignore.
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.
Is it possible (and wise) to check if a value exists in an external text file.
So if i have a file: bankcodes.txt that contains the next lines:
INGB
ABNA
...
Is it possible to check if a value is present in this file?
The reason is that these values can change and need to be easily changed whitout making a new jar file.
If there is another, wiser way of doing this i would like to hear it too.
From here:
https://stackoverflow.com/a/4716623/110933
Read contents of file line by line and check the value you get for "line" for the value you want:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
Give example how i did it , while File.txt -> our text and ourValue it the one we searching
String ourValue="value"
BufferedReader br = new BufferedReader(new FileReader("File.txt"));
String line = br.readLine();
boolean exist = false;
while (line != null&&!exist) {
if (ourValue.equals(line)) {
exist = true;
} else {
line = br.readLine();
}
}
System.out.println("the value " +ourValue+" exist in the Text? "+ exist);
}