What is the best way to replace a string in a while loop that reads lines from a file?
while ((line = reader.readLine()) != null) {
if (line.contains("blabla")) {
line = line.replaceAll("blabla", "eee");
}
writer.write(line);
}
is this correct way, I want to read all file lines, and check each line if contains this word, there is only one line that contains this word, if it contains it then replace this word and do not check another lines.
You can use a boolean flag as a condition in your while and update it in your if:
boolean found = false;
while ((!found) && ((line = reader.readLine()) != null)) {
if (found = line.contains("blabla")) {
line = line.replaceAll("blabla", "eee");
}
writer.write(line);
}
You can use replace this,
File your_file = new File(filePath)
String oldContent = “”;
BufferedReader reader = new BufferedReader(new FileReader(your_file));
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
String newContent = oldContent.replaceAll("wantToBeReplace", newString);
FileWriter writer = new FileWriter(your_file);
writer.write(newContent);
reader.close();
writer.close();
Related
I want to use mark() and reset() method to read the line before divider.
String line;
FileReader fr = new FileReader(PATH);
LineNumberReader br = new LineNumberReader(fr);
String DIVIDER = "================================";
while ((line = br.readLine()) != null) {
boolean endOfObj = false;
while (!line.trim().contains(DIVIDER)) {
br.mark(line.length());
line = br.readLine(); //return next line
}
br.reset();
line = br.readLine();
but line variable value is not the previous line of divider.
what is my problem is .
thank you
Could you try using the following code? I tidied up your code a bit, and put it into a method called getPreviousLine(). I got the feeling that you were getting hung up on using mark() and reset(), so I just relied on pure logic and state to find the line before the divider. If no divider is found, the method will return null.
String getPreviousLine(String PATH) {
String line;
FileReader fr = new FileReader(PATH);
LineNumberReader br = new LineNumberReader(fr);
String DIVIDER = "================================";
boolean endOfObj = false;
String previousLine = br.readLine();
if (previousLine == null) {
return null;
}
while ((line = br.readLine()) != null) {
if (line.trim().contains(DIVIDER)) {
endOfObj = true; // found the divider; break
break;
} else {
previousLine = line; // advance your line pointer
}
}
if (endOfObj) {
return previousLine;
} else {
return null;
}
}
I am using the following bufferedreader to read the lines of a file,
BufferedReader reader = new BufferedReader(new FileReader(somepath));
while ((line1 = reader.readLine()) != null)
{
//some code
}
Now, I want to skip reading the first line of the file and I don't want to use a counter line int lineno to keep a count of the lines.
How to do this?
You can try this
BufferedReader reader = new BufferedReader(new FileReader(somepath));
reader.readLine(); // this will read the first line
String line1=null;
while ((line1 = reader.readLine()) != null){ //loop will run from 2nd line
//some code
}
You can use the Stream skip() function, like this:
BufferedReader reader = new BufferedReader(new FileReader(somepath));
Stream<String> lines = reader.lines().skip(1);
lines.forEachOrdered(line -> {
...
});
File file = new File("path to file");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
int count = 0;
while((line = br.readLine()) != null) { // read through file line by line
if(count != 0) { // count == 0 means the first line
System.out.println("That's not the first line");
}
count++; // count increments as you read lines
}
br.close(); // do not forget to close the resources
Use a linenumberreader instead.
LineNumberReader reader = new LineNumberReader(new InputStreamReader(file.getInputStream()));
String line1;
while ((line1 = reader.readLine()) != null)
{
if(reader.getLineNumber()==1){
continue;
}
System.out.println(line1);
}
You can create a counter that contains the value of the starting line:
private final static START_LINE = 1;
BufferedReader reader = new BufferedReader(new FileReader(somepath));
int counter=START_LINE;
while ((line1 = reader.readLine()) != null) {
if(counter>START_LINE){
//your code here
}
counter++;
}
You can do it like this:
BufferedReader buf = new BufferedReader(new FileReader(fileName));
String line = null;
String[] wordsArray;
boolean skipFirstLine = true;
while(true){
line = buf.readLine();
if ( skipFirstLine){ // skip data header
skipFirstLine = false; continue;
}
if(line == null){
break;
}else{
wordsArray = line.split("\t");
}
buf.close();
I have the following code, which read thru the files and search for the line that start with subject and print out that line. But I only want to read the first line that contain the 'Subject' but currently it getting all the line that start with 'Subject' how can I configure such that it search for the first 'Subject' and print that one line ?
br = new BufferedReader(new FileReader("FilePath"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("Subject ")) {
System.out.println(line);
}
}
Use break; statement,
br = new BufferedReader(new FileReader("FilePath"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("Subject ")) {
System.out.println(line);
break;
}
}
You should try to use Regular Expressions to find all the occurrences of desired
Pattern i.e. something like "Subject*\n" in your case.
Check out this very good tutorial on Regex: www.vogella.com/tutorials/JavaRegularExpressions/article.html
You are not stopping your loop, so it will fetch until last line;
try this
if (line.startsWith("Subject ")) {
System.out.println(line);
break; // break the lop on success match
}
Using ArrayList you can save each line start with "Subject" and can traverse all of them you can use it according to your requirements
ArrayList<String> list = new ArrayList<String>();
br = new BufferedReader(new FileReader("FilePath"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("Subject ")) {
list.add(line);
}
}
System.out.println(list.get(0);
I am trying to read through a file and find the first line that contains the string "ua, ". I want to set that line to be equal to sCurrentLine. After that, I then want to set the next line in the file that contains "ua, " to be equal to sNextLine. Then I will process those line, and after that I want sCurrentLine to be equal to sNextLine and then the loop continues till the end of the file.
This is what I have so far
while ((line = br.readLine()) != null)
{
if (line.contains("ua, "))
{
sCurrentLine = line;
//now I don't know what to do
boolean currentLineSet = false;
while ((line = br.readLine()) != null)
{
if (line.contains("ua, "))
{
if (!currentLineSet) {
sCurrentLine = line;
currentLineSet = true;
} else {
sNextLine=line;
//processing
sCurrentLine = sNextLine;
}
}
You should use an ArrayList which will contain Strings.
ArrayList<String> st = new ArrayString<String>();
while ((line = br.readLine()) != null)
{
if (line.contains("ua, "))
{
st.add(line);
}
}
Since you don't know the number of lines that will contain the "ua, " String, you should use an ArrayList.
Now you'll have the lines that contains "ua, " in the ArrayList st.
OP EDIT
If you want to process two lines, you can save the first line you find with "ua, " and then read another line, check if it contains this String:
String st1, st2;
while ((line = br.readLine()) != null)
{
if (line.contains("ua, "))
{
st1 = line;
}
if ((line = br.readLine()) != null && line.contains("ua, "))
{
st2 = line;
}
}
Of course you can set flags to see whether the first and second lines contained the String.
int index, iCurrentLine = 1;
while ((line = br.readLine()) != null)
{
index++;
if (line.contains("ua, ")) {
sCurrentLine = line;
iCurrentLine = index;
}
}
Loop through the file contents again, then make sure that the new index doesn't equal the previous index, then just set sNextLine = line;
I have some code to read the lines from a file, I would like to recognize when the line starts or the fisrt character (not blank) is '*' and ignore it, so inside the while statement add something like
if(line[0]=='*')
ignore that line
I have something like:
input = new BufferedReader(new FileReader(new File(finaName)));
String line = null;
while ((line = input.readLine()) != null) {
String[] words = line.split(" ");
....
}
How to complete the code?
input = new BufferedReader(new FileReader(new File(finaName)));
String line = null;
while ((line = input.readLine()) != null) {
if(line.trim().indexOf('*') == 0)
continue;
String[] words = line.split(" ");
....
}
Change your while loop as:
while((line = input.readLine()) != null){
if(!line.startsWith("*")){
String[] words = line.split(" ");
....
}
}
EDIT
If "*" is not in the beginning of the line but at some position in the line, use the following
if(line.indexOf("*") == position){
......
}
where position can be an integer specifying the position you are interested in.
Assuming the * marks and end of line comment, this loop will keep anything needed on the line before it.
input = new BufferedReader(new FileReader(new File(finaName)));
String line = null;
char[] lineChars;
while ((line = input.readLine()) != null) {
lineChars = line.toCharArray();
line = "";
for(char c: lineChars){
if(c == '*')break;
line.concat(Character.toString(c));
}
if(!line.equals(""))
String[] words = line.split(" ");
}