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;
}
}
Related
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();
I have a text file and I need to check if it is correct. The file should be of the type:
XYab
XYab
XYab
Where X,Y,a,b can take only a certain range of value. For example b must be a value between 1 and 8. These values are defined by 4 enum (1 enum for X,1 enum for Y, etc..). The only thing that came to my mind is something like this:
BufferedReader br = new BufferedReader(new FileReader(FILENAME)
String s;
while ((s = br.readLine()) != null) {
if(s.charAt(0)==Enum.example.asChar())
}
But of course it checks only the first line of the file. Any advice on how I can check all the file's lines?
You could try something like this, (modify it according to yours enums)
#Test
public void findDates() {
File file = new File("pathToFile");
try{
Assert.assertTrue(validateFile(file));
}catch(Exception ex){
ex.printStackTrace();
}
}
private boolean validateFile(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
// add yours enumns to one list
List<Enum> enums = new ArrayList<>();
enums.add(EnumX);
enums.add(EnumY);
enums.add(EnumA);
enums.add(EnumB);
while ((line = br.readLine()) != null) {
// process the line.
if(line.length() > 4){
return false;
}
//for each position check if the value is valid for the enum
for(int i = 0; i < 4; i++){
if(enums.get(i)).valueOf(line.charAt(i)) == null){
return false;
}
}
}
return true;
}
Don't forget about collision but if you have number or string you can use the regexp to do that.
On each Enum you have to do a function regexp like this. You can use an external Helper instead.
enum EnumX {
A,B,C,D, ...;
...
// you enum start to 0
public static String regexp(){
return "[0-" + EnumX.values().length +"]";
}
}
// it is working also if you have string in your file
enum EnumY{
A("toto"),B("titi"),C("tata"),D("loto");
public static String regexp(){
StringBuilder regexp = new StringBuilder("[");
for(EnumY value : EnumY.values()){
regexp.append(value).append(",");
}
regexp.replace(regexp.length()-1, regexp.length(), "]");
return regexp.toString();
}
}
public boolean isCorrect(File file){
// build the regexp
String regexp = EnumX.regexp() + EnumY.regexp() + EnumA.regexp() +EnumB.regexp();
// read the file
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (line.matches(regexp) == false){
// this line is not correct
return false;
}
}
return true;
}
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();
My problems is that I have to arrange, when searching for a customer, arrange the while loop to only examine every fourth line read.
This is the code I already have on this problem:
BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;
while ((line = br.readLine()) != null)
{
...
}
br.close();
Does anybody know what needs to be at the place of "..."?
Thanks!
Something along the lines of
int i = 0;
while ((line = br.readLine()) != null)
{
i++;
if (i % 4 == 0)
{
// if i is divisible by 4, then
// your actual code will get executed
...
}
}
Just call br.readLine() 3 times at the end of the loop, discarding the output:
BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;
while ((line = br.readLine()) != null)
{
...
for(int i=0;i<3;i++){ br.readLine(); }
}
br.close();
BufferedReader br = new BufferedReader(new FileReader("Customers.txt"));
String line;
int count 0;
while ((line = br.readLine()) != null)
{
if (count!=3)
count++;
else {
// Do something?
count=0;
}
}
br.close();
I have a DB that usually generates a file with 3000 lines, actually I want to count the number of LAYERID(s)
My DB file is like this :
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=FALSE,GBPATH=AAP4,GTXT=12;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_02,USFGN=DISABLED;
CREATE BUTYP=ACB9T,RAAT=TRUE,GBPATH=AAP4,GTXT=32;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_02,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_03,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_03,USFGN=DISABLED;
CREATE BUTYP=ACB2T,RAAT=TRUE,GBPATH=AAP4,GTXT=1;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=FALSE,GBPATH=AAP4,GTXT=2;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=TRUE,GBPATH=AAP4,GTXT=3;
if we just have "LAYID=LY_00" (like the first line) we must ignore it, but if under the "LAYID=LY_00" be "LAYID=LY_01 and ..." (like the third line) we must count "LAYID=LY_00" and others layerids,for example in line 3 till line 6 we have 4 Layeids
LAYID=LY_00
LAYID=LY_01
LAYID=LY_01
LAYID=LY_02
So count is 4 and if we want to count all of them we have 9, As I said before, if we just have
LAYID=LY_00 simillar line 1 we ignore it.
Also I wrote this method for read line by line :
public void execToken(File f) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer strt = new StringTokenizer(line, ";");
while (strt.hasMoreTokens()) {
String token = strt.nextToken();
layerSupport(token);
}
}
}
and, I know the below method is not true and complete yet, but it's maybe useful for you
public void layerSupport(String token){
if(token.startsWith("CREATE TRMD") && !token.contains("LAYID=LY_00"))
System.out.println(token) ;
}
many thanks for your help ...
public int execToken(File f) throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
int count = 0;
Pattern layID = Pattern.compile("LAYID=LY_\\d+");
Matcher matcher = null;
boolean isSingle = true;
while ((line = br.readLine()) != null)
{
if(line.contains("LAYID=LY_00"))
{
isSingle = false;
continue;
}
matcher = layID.matcher(line);
if(matcher.find())
{
count++;
if(!isSingle)
count++;
}
isSingle = true;
}
return count;
}
try this.it remembers if previous line contains LAYID=LY_00 and increments count twice in next iteration, if LAYID=LY_<digits> was found and isSingle is false.
Something like that:
public int execToken(File f) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(f));
int count = 0;
String line;
String previousLine = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("CREATE TRMD")) {
if (!previousLine.isEmpty()) {
count += (previousLine.contains("LAYID=LY_00") ? 2 : 1);
}
previousLine = line;
} else {
previousLine = "";
}
}
return count;
}
Not tested.