Stuck in while loop with BufferedReader-java - java

I'm completely at a lose for why this isn't working. I've had similar loops before and they've worked fine.
try{
text = new BufferedReader(new FileReader(fileName));
while ((lineOfText = text.readLine()) != null){
StringTokenizer tokens = new StringTokenizer(lineOfText," , .;:\"&!?-_\n\t12345678910[]{}()##$%^*/+-");
while (tokens.hasMoreTokens()){
countTotalWordsInDocument++;
String word = tokens.nextToken();
countTotalCharactersInAllWords = countTotalCharactersInAllWords + word.length();
}
}
text.close();
} catch (IOException e) {
System.out.println("file not found");
}

Related

Find a word and return specific value of the word

I have a file with this content:
1.10.100.1 1000.0
1.10.100.2 2000.0
1.10.100.3 2000.0
1.10.500.4 1000.0
i wrote the function that find the specific string in the file:
public double searchInBalance(String depositNumber) {
try {
String[] words = null;
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String string;
String inputBalanceToFind = depositNumber;
while ((string = bufferedReader.readLine()) != null) {
words = string.split(" ");
for (String word : words) {
if (word.equals(inputBalanceToFind)) {
System.out.println("string :" + string);
}
}
}
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in searchInBalance");
}
return 1;
}
i want to make a function that when find the left value of the file return the right value(the double value) back but have no idea how to do that please help me
public double searchInBalance(String depositNumber){
try {
String[] words = null;
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String string;
String inputBalanceToFind = depositNumber;
while ((string = bufferedReader.readLine()) != null) {
words = string.split(" ");
for (int i = 1; i < words.length; i += 2) {
if (words[i].equals(inputBalanceToFind)) {
System.out.println(words[i]+" - "+words[i - 1]);
}
}
}
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in searchInBalance");
}
}
Just make a for loop with a counter to work with the indexes of the Array. But this is not a good programming style and you should try to improve your solution :D

CTRL +F Logic in java

I want to search the specific word in the text file and store that word in the array list. I have done like this but it gives output like word exist in the text file or not. I want to store that text in the array list
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
try {
br = new BufferedReader(new FileReader(filePath));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
}
}
if (countBuffer > 0) {
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
List<String> searchedWords = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
if(!searchedWords.contains(word)){
searchedWords.add(word);
}
}
}
if (countBuffer > 0) {
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("Words that you have searched and found:");
for(String word : searchedWords){
System.out.println(word);
}
You will have an arraylist searchedWords which will keep track of the searched words, you will notice that the if statement will not allow duplicates in the arraylist, so if you want to allow duplicates just remove the if(!searchedWords.contains(word)) and just write searchedWords.add(word);.
You can define a String ArrayList with your other declarations using:
ArrayList<String> matches = new ArrayList<String>();
Then when you find a word that matches, add it to the ArrayList using:
matches.add(word);
Edit:
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = "";
String filePath = "D:\\PDFTOEXCEL\\Extractionfrompdf.txt";
BufferedReader br;
String inputSearch = "Facture";
String line = "";
ArrayList<String> matches = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(inputSearch)) {
count++;
countBuffer++;
matches.add(word);
}
}
if (countBuffer > 0) {
countBuffer = 0;
lineNumber += countLine + ",";
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Reading specific line fromt .txt file in android

I've got the file, which can vary in size, in terms of lines. The only thing I know is that it's made of same modules of, lets say, 7 lines. So it means that .txt can be 7, 14, 21, 70, 77 etc. lines. I need to get only header of each module - line 0, 7 and so on.
I've written this code for the job:
textFile = new File(Environment.getExternalStorageDirectory() + "/WorkingDir/" + "modules.txt" );
List<String> headers = new ArrayList<>();
if (textFile.exists()) {
try {
FileInputStream fs= new FileInputStream(textFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(fs));
int lines = 0;
int headLine = 0;
while (reader.readLine() != null) { lines++;}
Log.i("Debug", Integer.toString(lines));
while(headLine < lines){
for (int i = 0; i < dateLine - 1; i++)
{
reader.readLine();
Log.i("Debug", reader.readLine());
}
headers.add(reader.readLine());
headLine += 7;
}
Log.i("Debug", headers.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is that it always returns [null]. I do not know where's the problem, since I used similar questions from overflow as references.
ArrayList<String> headerLines = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
// process the line.
if(lineCount % 7 == 0) {
heaaderLines.add(line);
}
lineCount ++;
}
} catch (IOException ioEx) {
ioEx.printStackTrace();
} finally {
br.close();
}

Java Read/Write, Rename File having issue

I was using my code to do a replace line feature. It was working initially but suddenly my new file became blank and the code did not bring me back to the AdminMenu(), as well as the file not being renamed. There is also another issue where if I use "\r\n" there will be a blank line on top of my file which I am trying to remove. I tried using \n after totalChips, but it doesn't seem to work. I could use some advice on this.
output
<Blank File>
expected output
Line1|password|500
Line2|password|600
//ModifiedLine can be either line based on UserName
codes are below
public static void AddChips() {
File oldFileName = new File("players.dat");
File tmpFileName = new File("newplayers.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN))
line = Username + "|" + Password + "|" + totalChips;
bw.write("\r\n"+line);
}
bw.close();
br.close();
oldFileName.delete();
tmpFileName.renameTo(oldFileName);
AdminMenu();
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
new Error
java.lang.ArrayIndexOutOfBoundsException: 1
at testcode.AddChips(testcode.java:53)
at testcode.main(testcode.java:11)

Output only giving me one line

Can anyone point me in the right direction here. I have a method that is supposed to read a file and display the data in that file. I can only get it to display one line. I know it is something simple I am over looking, but my brain is mush and I just keep digging a bigger hole.
public static String readFile(String file) {
String data = "";
if (!new java.io.File(file).exists()) {
return data;
}
File f = new File(file);
FileInputStream fStream = null;
BufferedInputStream bStream = null;
BufferedReader bReader = null;
StringBuffer buff = new StringBuffer();
try {
fStream = new FileInputStream(f);
bStream = new BufferedInputStream(fStream);
bReader = new BufferedReader(new InputStreamReader(bStream));
String line = "";
while (bStream.available() != 0) {
line = bReader.readLine();
if (line.length() > 0) {
if (line.contains("<br/>")) {
line = line.replaceAll("<br/>", " ");
String tempLine = "";
while ((tempLine.trim().length() < 1)
&& bStream.available() != 0) {
tempLine = bReader.readLine();
}
line = line + tempLine;
}
buff.append(line + "\n");
}
}
fStream.close();
bStream.close();
bReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buff.toString();
}
String line = null;
while ((line = bReader.readLine())!=null)
How about doing this with Guava:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html
List<String> lines = Files.readLines("myFile.txt", Charset.forName("UTF-8"));
System.out.println(lines);
You'd still have to do a little bit of work to concatenate the <br> lines etc...

Categories