we are supposed to create a program that reads a word from a JTextField and compare it to a list, then we have to count how many lines to the word if it exist and display the same line from another text file in the same program into another JTextField (it's supposed to be a Dictionary of some sort) here is what i have:
boton1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String palabra=tx1.getText();
boton3.setEnabled(true);
try{
// here is where i open my file
FileInputStream fstream = new FileInputStream("src/archivos/translator.txt");
DataInputStream entrada = new DataInputStream(fstream);
BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
String strLinea;
while ((strLinea = buffer.readLine()) != null) {
System.out.println (strLinea);
int i=0;
while (!(strLinea.equals(palabra))){
i++;
}
tx2.setText(String.valueOf(i));
}
entrada.close();
}catch (IOException x){
System.err.println("Oh no, ocurriĆ³ un error: " + x.getMessage());
}
}} );
Based on my understanding of what you said, first, you should change:
while (!(strLinea.equals(palabra))){
to
while (!(strLinea.contains(palabra))){
You want to see if the line contains that word, not that the line is the same as the contents of the TextArea. Also, you'll want to add another statement to the contents of that while loop. Currently it'll just increment "i" forever if the word doesn't come up in the document. You want it to move strLinea to the next line if the current one doesn't have it, and if it does, you'll then want to terminate the loop.
I think your problem is
while ((strLinea = buffer.readLine()) != null) {
System.out.println (strLinea);
int i=0;
while (!(strLinea.equals(palabra))){
i++;
}
tx2.setText(String.valueOf(i));
}
In inner while loop, you are iterating forever. If you want to compare each word in the file to the JTextField value, you should write
int i = 0;
while ((strLinea = buffer.readLine()) != null) {
i++;
System.out.println (i + " " + strLinea);
if (strLinea.equals(palabra)){
tx2.setText(String.valueOf(i));
break;
}
}
Related
I read about someone having troubles with BufferedReader: the reader simply do not read the first lines. I have instead the opposite problem. For example, in a text file with 300 lines, it arrives at 200, read it half of it and then the following string is given null, so it stops.
private void readerMethod(File fileList) throws IOException {
BigInteger steps = BigInteger.ZERO;
BufferedReader br = new BufferedReader(new FileReader(fileList));
String st;
//reading file line by line
try{
while (true){
st = br.readLine();
if(st == null){
System.out.println("Null string at line " + steps);
break;
}
System.out.println(steps + " - " + st);
steps = steps.add(BigInteger.ONE);
}
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
br.close();
}catch(Exception e){}
}
}
The output of the previous slice of code is as expected until it reaches line 199 (starting from 0). Consider a file with 300 lines.
...
198 - 3B02D5D572B66A82F9D21EE809320DB3E250C6C9
199 - 6E2C69795CB712C27C4097119CE2C5765
Null string at line 200
Notice that, all lines have the same length, so in this output line 199 is not even complete. I checked the file text, and it's correct: it contains all 300 lines and they are all of the same length. Also, in the text there are only capitals letters and numbers, as you can see.
My question is: how can i fix this? I need that the BufferedReader read all the text, not just a part of it.
As someone asked i add here the remaining part of the code. Please notice that all capital names are constant of various type (int, string etc).
This is the method that is called by the main thread:
public void init(){
BufferedWriter bw = null;
List<String> allLines = createRandomStringLines(LINES);
try{
String fileName = "SHA1_encode_text.txt";
File logFile = new File(fileName);
System.out.println(logFile.getCanonicalPath());
bw = new BufferedWriter(new FileWriter(logFile));
for(int i = 0; i < allLines.size(); i++){
//write file
String o = sha1FromString(allLines.get(i));
//sha1FromString is a method that change the aspect of the string,
//replacing char by char. Is not important at the moment.
bw.write(o + "\n");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
bw.close();
}catch(Exception e){}
}
}
The method that create the list of random string is the following. "SYMBOLS" is just a String contains all avaiable chars.
private List<String> createRandomStringLines(int i) {
List<String> list = new ArrayList<String>();
while(i!=0){
StringBuilder builder = new StringBuilder();
int count = 64;
while (count-- != 0) {
int character = (int)(Math.random()*SYMBOLS.length());
builder.append(SYMBOLS.charAt(character));
}
String generatedString = builder.toString();
list.add(generatedString);
i--;
}
return list;
}
Note that, the file written is totally correct.
Okay, thanks to the user ygor, i manage to resolve it. The problem was that the BufferReader stars his job when the BufferWriter isn't closed yet. It was sufficient to move the command line that require the reader to work, after the bufferWriter.close() command.
I am new in java. I just wants to read each string in java and print it on console.
Code:
public static void main(String[] args) throws Exception {
File file = new File("/Users/OntologyFile.txt");
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(
fstream));
String data = new String();
while ((data = infile.readLine()) != null) { // use if for reading just 1 line
System.out.println(""+data);
}
} catch (IOException e) {
// Error
}
}
If file contains:
Add label abc to xyz
Add instance cdd to pqr
I want to read each word from file and print it to a new line, e.g.
Add
label
abc
...
And afterwards, I want to extract the index of a specific string, for instance get the index of abc.
Can anyone please help me?
It sounds like you want to be able to do two things:
Print all words inside the file
Search the index of a specific word
In that case, I would suggest scanning all lines, splitting by any whitespace character (space, tab, etc.) and storing in a collection so you can later on search for it. Not the question is - can you have repeats and in that case which index would you like to print? The first? The last? All of them?
Assuming words are unique, you can simply do:
public static void main(String[] args) throws Exception {
File file = new File("/Users/OntologyFile.txt");
ArrayList<String> words = new ArrayList<String>();
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(
fstream));
String data = null;
while ((data = infile.readLine()) != null) {
for (String word : data.split("\\s+") {
words.add(word);
System.out.println(word);
}
}
} catch (IOException e) {
// Error
}
// search for the index of abc:
for (int i = 0; i < words.size(); i++) {
if (words.get(i).equals("abc")) {
System.out.println("abc index is " + i);
break;
}
}
}
If you don't break, it'll print every index of abc (if words are not unique). You could of course optimize it more if the set of words is very large, but for a small amount of data, this should suffice.
Of course, if you know in advance which words' indices you'd like to print, you could forego the extra data structure (the ArrayList) and simply print that as you scan the file, unless you want the printings (of words and specific indices) to be separate in output.
Split the String received for any whitespace with the regex \\s+ and print out the resultant data with a for loop.
public static void main(String[] args) { // Don't make main throw an exception
File file = new File("/Users/OntologyFile.txt");
try {
FileInputStream fstream = new FileInputStream(file);
BufferedReader infile = new BufferedReader(new InputStreamReader(fstream));
String data;
while ((data = infile.readLine()) != null) {
String[] words = data.split("\\s+"); // Split on whitespace
for (String word : words) { // Iterate through info
System.out.println(word); // Print it
}
}
} catch (IOException e) {
// Probably best to actually have this on there
System.err.println("Error found.");
e.printStackTrace();
}
}
Just add a for-each loop before printing the output :-
while ((data = infile.readLine()) != null) { // use if for reading just 1 line
for(String temp : data.split(" "))
System.out.println(temp); // no need to concatenate the empty string.
}
This will automatically print the individual strings, obtained from each String line read from the file, in a new line.
And afterwards, I want to extract the index of a specific string, for
instance get the index of abc.
I don't know what index are you actually talking about. But, if you want to take the index from the individual lines being read, then add a temporary variable with count initialised to 0.
Increment it till d equals abc here. Like,
int count = 0;
for(String temp : data.split(" ")){
count++;
if("abc".equals(temp))
System.out.println("Index of abc is : "+count);
System.out.println(temp);
}
Use Split() Function available in Class String.. You may manipulate according to your need.
or
use length keyword to iterate throughout the complete line
and if any non- alphabet character get the substring()and write it to the new line.
List<String> words = new ArrayList<String>();
while ((data = infile.readLine()) != null) {
for(String d : data.split(" ")) {
System.out.println(""+d);
}
words.addAll(Arrays.asList(data));
}
//words List will hold all the words. Do words.indexOf("abc") to get index
if(words.indexOf("abc") < 0) {
System.out.println("word not present");
} else {
System.out.println("word present at index " + words.indexOf("abc"))
}
I am not sure what went wrong but the printout only give me completely the information form the txt file only on the second time. The first time it will only print out the first line that is in my txt file. Hope someone can point out my mistake.
Here's my code:
public static void main(String[]args) {
try {
FileReader fileReader = new FileReader("data_file/Contact.txt");
BufferedReader in = new BufferedReader(fileReader);
String currentContact = in.readLine();
StringBuilder sb = new StringBuilder();
while(currentContact != null) {
StringBuilder current = sb.append(currentContact);
current.append(System.getProperty("line.separator"));
JOptionPane.showMessageDialog(null, "Contact : \n" + current);
// System.out.println("Contact:" + currentContact);
currentContact = in.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Move
JOptionPane.showMessageDialog(null, "Contact : \n" + current);
outside your while loop (and change it to use sb rather than current). That will show the dialog only after the whole file has been read. Right now you're showing a dialog for each line in your input file.
Incidentally, you could replace this:
StringBuilder current = sb.append(currentContact);
current.append(System.getProperty("line.separator"));
with this:
sb.append(currentContact);
sb.append(System.getProperty("line.separator"));
or even do it on one line:
sb.append(currentContact).append(System.getProperty("line.separator"));
StringBuffer.append returns the object that it is called on. This allows you to chain calls to append.
So I'm having an issue reading a text file into my program. Here is the code:
try {
InputStream fis = new FileInputStream(targetsFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//while(br.readLine()!=null){
for (int i = 0; i < 100; i++) {
String[] words = br.readLine().split(" ");
int targetX = Integer.parseInt(words[0]);
int targetY = Integer.parseInt(words[1]);
int targetW = Integer.parseInt(words[2]);
int targetH = Integer.parseInt(words[3]);
int targetHits = Integer.parseInt(words[4]);
Target a = new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
} catch (Exception e) {
System.err.println("Error: Target File Cannot Be Read");
}
The file I am reading from is 100 lines of arguments. If I use a for loop it works perfectly. If I use the while statement (the one commented out above the for loop) it stops at 50. There is a possibility that a user can run the program with a file that has any number of lines, so my current for loop implementation won't work.
Why does the line while(br.readLine()!=null) stop at 50? I checked the text file and there is nothing that would hang it up.
I don't get any errors from the try-catch when I use the while loop so I am stumped. Anyone have any ideas?
also very comprehensive...
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
You're calling br.readLine() a second time inside the loop.
Therefore, you end up reading two lines each time you go around.
You can use a structure like the following:
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
In case if you are still stumbling over this question.
Nowadays things look nicer with Java 8:
try {
Files.lines(Paths.get(targetsFile)).forEach(
s -> {
System.out.println(s);
// do more stuff with s
}
);
} catch (IOException exc) {
exc.printStackTrace();
}
Thank you to SLaks and jpm for their help. It was a pretty simple error that I simply did not see.
As SLaks pointed out, br.readLine() was being called twice each loop which made the program only get half of the values. Here is the fixed code:
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
String words[]=new String[5];
String line=null;
while((line=br.readLine())!=null){
words=line.split(" ");
int targetX=Integer.parseInt(words[0]);
int targetY=Integer.parseInt(words[1]);
int targetW=Integer.parseInt(words[2]);
int targetH=Integer.parseInt(words[3]);
int targetHits=Integer.parseInt(words[4]);
Target a=new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
Thanks again! You guys are great!
Concept Solution:br.read() returns particular character's int value so loop
continue's until we won't get -1 as int value and Hence up to there it prints
br.readLine() which returns a line into String form.
//Way 1:
while(br.read()!=-1)
{
//continues loop until we won't get int value as a -1
System.out.println(br.readLine());
}
//Way 2:
while((line=br.readLine())!=null)
{
System.out.println(line);
}
//Way 3:
for(String line=br.readLine();line!=null;line=br.readLine())
{
System.out.println(line);
}
Way 4:
It's an advance way to read file using collection and arrays concept
How we iterate using for each loop.
check it here
http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html
In addition to the answer given by #ramin, if you already have BufferedReader or InputStream, it's possible to iterate through lines like this:
reader.lines().forEach(line -> {
//...
});
or if you need to process it with given order:
reader.lines().forEachOrdered(line -> {
//...
});
Basically, i need to check for a word's occurances within multiple files.
Also, a word might exist in a single text file multiple times.
I want to save positions of a word for each file; so i wrote the code below:
public static void findWord(String word, File file){
try{
BufferedReader input = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String line;
ArrayList<Integer> list=new ArrayList<Integer>();
while((line=input.readLine())!=null){
if(line.indexOf(word)>-1){
list.add(line.indexOf(word));
}
}
System.out.println(file +": "+ list);
input.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
My code fails to add to list after first successful occurance. So I have only one element within every array.
How do i fix it?
P.S My text files consists of one line
Here goes the fix (replace your while loop with this):
while ((line = input.readLine ()) != null)
{
int index = -1;
while ((index = line.indexOf (word, index + 1) > -1)
{
list.add (index);
}
}