JavaFX reading a text file and displaying it to multiple text fields - java

I have a text file with 4 lines of random words, line for line, and I need to be able to read each line and display it to its text field (First line goes into first text field, etc), but it is only reading the last line and displaying it into any text field.
"myfile.txt"
one
two
three
onetwothree
TextField label1Text = new TextField();
TextField label2Text = new TextField();
TextField label3Text = new TextField();
load.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent l) {
String line = "";
try {
BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"));
while ((line = reader.readLine()) != null) {
label1Text.setText(line);
label2Text.setText(line);
label3Text.setText(line);
labelO2Text.setText(line);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
primaryStage.show();
}
}

Your current code reads each line in turn, and for each line sets the text of all the labels to that line of text.
Instead, you need to take each label in turn, and set its text to the next line from the file. You can do that with something like:
try (BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"))) {
List.of(label1Text, label2Text, label3Text, label02Text)
.forEach(label -> {
try {
label.setText(reader.readLine());
} catch (IOException exc) {
// handle exception
}
});
}

You are reading a single line, then setting the content of that line to all 3/4 TextFields (there is one missing in your example). After the loop finishes, all TextFields are set to the content of the last line of your file.
There is a variety of ways to achieve what you want - if you only ever have 4 entries, the following will work:
String[] lines = new String[4];
int index = 0;
while ((line = reader.readLine()) != null) {
lines[index++] = line;
if (index==4) break;
}
label1Text.setText(lines[0]);
label2Text.setText(lines[1]);
label3Text.setText(lines[2]);
label4Text.setText(lines[3]);
If you had references to your TextFields in an array, you could also do
int index = 0;
while ((line = reader.readLine()) != null) {
labels[index++].setText(line);
if (index==4) break;
}

The problem sits in your loop
while ((line = reader.readLine()) != null) {
label1Text.setText(line);
label2Text.setText(line);
label3Text.setText(line);
labelO2Text.setText(line);
}
Basically if we look at the loop, first iteration changes all of the labels to the word "One", second iteration in the loop sets all the labels to "Two", than "Three" and last iteration sets all labels as "Four".
To solve the problem you can add a simple counter with some if statements, so it will tell your loop what to do.
int counter = 0;
while ((line = reader.readLine()) != null) {
if(counter == 0)
label1Text.setText(line);
if(counter == 1)
label2Text.setText(line);
if(counter == 2)
label3Text.setText(line);
if(counter == 3)
labelO2Text.setText(line);
counter++;
}
I am sure it is not the most optimal way, but if you want to do it with loop, that's it.

Related

how to read csv file without specific number of column in java and without change the code after every additional column

I tried to write code to read csv file, and I stored the data in an array of object
but after every change in the number of columns, I should read another column and change the code.
because I want to use the same class for different csv files with different number of columns without need to change the code for every file.
public class Read_CSV {
public static Object[][]readCSVdata(String csvFilePath){
//String csvFilePath = null;
ArrayList<Object[]>dataList = new ArrayList <Object[]>();
String line = "";
String cvsSplitBy = ",";
try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
int iteration = 0;
while ((line = br.readLine()) != null) {
if(iteration == 0) {
iteration++;
continue;
}
String[] arri = line.split(cvsSplitBy);
Object[]arri1= {arri[0] , arri[1],arri[2] };
//here after every additional column I should add another cell
dataList.add(arri1);
}
br.close();
return dataList.toArray(new Object[dataList.size()][]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
You could use the array of strings after splitting each line:
while ((line = br.readLine()) != null) {
if(iteration == 0) {
iteration++;
continue;
}
String[] arri = line.split(cvsSplitBy);
dataList.add(arri);
}
Then dataList will contain arrays of strings.
Or you have some other requirements?

How to read a file from a specific line to another specific line?

So I'm trying to make a file reader to read from x line to y line but when i execute the program it reads all the lines of the file and not the lines that should have started and ended, For example if i'm looking an ID in the file it should print de ID, The name of the holder(the next line of the ID Line), and his/her address(Next line of the name Line), but instead of print just that it prints all the ID'S, Names and Addresses of everyone in the file.
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line2;
int count = 0;
try {
BufferedReader input = new BufferedReader(new FileReader(file));
Scanner input2 = new Scanner(file);
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while((line2 = input.readLine()) != null)
{
if(line2.contains(CL.getID()))
{
while(((line2 = readers.readLine()) != null) && readers.getLineNumber() <= count + 3)
{
count++;
System.out.println(line2);
}
input.close();
input2.close();
output.close();
readers.close();
break;
}
}
}catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
I've modified your code because the problem was at the count++ which will eventually led to reading all the lines from your files, and at the line2 = readers.readLine() which will read from the first line of the file again ( the program works half correct because it reads only 3 lines and only if line2 contains your ID ). Now, to make your program work correctly, you need to either use the BufferedReader or the LineNumberReader.
public static void main(String[] args) {
System.out.println("Escriba el ID Del Cliente");
String line2;
File file = new File(yourpathhere);
int lineCount = 0;
try {
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((line2 = readers.readLine()) != null) {
lineCount++;
if (line2.contains(CL.getId())) {
while (line2 != null && readers.getLineNumber() <= lineCount + 3) {
System.out.println(line2);
line2 = readers.readLine();
}
output.close();
readers.close();
break;
}
}
} catch (IOException ex) {
System.out.println("ERRORR!!!!!!");
}
}
PS : pay attention for the getLineNumber() method because it increments the lines read until the moment you're calling it. It means that if we didn't had the lineCount and the ID we're trying to find was at the 6th line, the getLineNumber() value at the moment when line2.contains(CL.getId()) == true was 6, so the readers.getLineNumber() <= 3 will be FALSE and the program won't work correctly anymore. ( We need to keep track for the lines read until the moment we check for the id )
Assuming you have a file with 100 lines and you want to check and print out line 5 to 10 you could try this:
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line;
int count = 0;
int xLine = 5;
int yLine = 10;
try (BufferedReader input = new BufferedReader(new FileReader(file)))
{
while((line = input.readLine()) != null)
{
if(count < xLine)
{
// skip all lines lower then start
continue;
}
else if(count >= xLine && count <= yLine && line.contains(CL.getID()))
{
// print line if line is between lines to read
// and if line contains ID
System.out.println(line);
}
else
{
// break if count is bigger then yLine
break;
}
count++;
}
}
catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
You read all lines till the BufferedReader reaches null. You check if the line contains your ID. Then you check if the count is between the linenumbers you want to check / print. Then you increment the count for the lines processed.
I simplified the try-catch-Block with a try-with-ressources Statement. As for now I don't see what your plans with output and scanner were, so I removed them.

Search in file using split

I have a users1.txt with some registries like: basketball president tom#gmail.com 1234 and I am making the user to give as input the email,password and two choices of spinner , and I want to search them in the file and compare them , then if its true i will print a message (open() function). In the bellow code the condition was made with success but only for the first line of the file, I want to check all the file for each input of user. To be more specific , I want the search not to stop to basketball president tom#gmail.com 1234 but continues to the second line football referee tam#gmail.com 123123 etc. until the end of file. any suggestion would be great.
signBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if( TextUtils.isEmpty(email.getText()))
email.setError("Email Required");
else if( TextUtils.isEmpty(password.getText()))
password.setError("Password Required");
else {
String text = readFromFile("users1.txt");
String[] splited = text.split("\\s+");
if(SportSpinner.getSelectedItem().toString().equals(splited[0]) && (UserSpinner.getSelectedItem().toString().equals(splited[1])) && (password.getText().toString().equals(splited[3])) && (email.getText().toString().equals(splited[2])))
open(SportSpinner.getSelectedItem().toString(), UserSpinner.getSelectedItem().toString());
else
{
if(tries==1)
open();
signBtn.startAnimation(shakeAnimation);
tries--;
message(tries);
}
}
}
});
}
private String readFromFile(String name){
StringBuilder text = new StringBuilder();
try {
File file = new File(getFilesDir().getAbsolutePath(),name);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}catch(IOException e){
Log.e("Exception", "File read failed: " + e.toString());
}
return String.valueOf(text);
}
If the lines for the file are always in sets of the same number, you can use a loop to increment the indices that you check. I would also add a flag of some sort to stop searching if you found it.
boolean found = false;
for (int i = 0; i <= splitted.length-3 && !found; i += 4) {
if(SportSpinner.getSelectedItem().toString().equals(splited[i]) && (UserSpinner.getSelectedItem().toString().equals(splited[i+1])) && (password.getText().toString().equals(splited[i+3])) && (email.getText().toString().equals(splited[i+2]))) {
found = true;
// Your open method goes here
}
}
if (!found) {
// Now put all the code from the previous else statement here, since it has now searched the whole list for the one set of inputs
}
This checks every line of the file for a match and drops out of the loop if there is a match.

Read File in Java, output the first comma delimited String

I want to extract the first String in a file using the delimiter ",".
Why does this code generate a number of lines greater than one?
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("irisAfter.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
for (int i =0; i<splited.length;i++) {
System.out.println(splited[0]);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) { e.printStackTrace(); }
}
}
You are printing inside a loop. That's why it is printing multiple times (if that's what you're asking).
String[] splited = read.split(",");
System.out.println(splited[0]);
will just do
EDIT: As Abishek also mentioned, don't read = in.readLine(); again inside your while loop since by doing so you are skipping a line.
while ((read = in.readLine()) != null) {
String[] splited = read.split(",");
System.out.println(splited[0]);
}
What do you mean by number of lines superior to the original ones
If you are using splited[0], why are you keeping inside a loop. It will always get you same string
Not sure why your code works that way but you might try Scanner with a delimeter. Try:
Scanner sc = new Scanner( new File("myNumbers")).useDelimiter(",");
String firstString = sc.next();
/// check for null..
You read in every line from "irisAfter.txt", then split each line on "," into multiple elements, then print out the first element of that line on its own line as many times as there are elements in the line. Multiple lines*multiple elements per line = more lines in output than in input.
Change
for (int i =0; i<splited.length;i++) {
System.out.println(splited[0]);
}
to
if (splited.length > 0)
{
System.out.println(splited[0]);
}
That way you print out the first element of every line on its own line only one time and only if there actually is a first element.
You are also skipping every other line. If you don't want to do that, remove the line
read = in.readLine();
just below
while ((read = in.readLine()) != null) {.
(You are now reading in a line and then reading in the next line, discarding the first read in line. Then you process that second line, after which the loop starts again, you read in the third line, then read in the fourth line, discarding the third, etc. etc.)
if you modify your code like this, you should get the result you expect.
public static void main(String[] args) {
BufferedReader in = null;
try {
String[] splited;
in = new BufferedReader(new FileReader("irisAfter.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
splited = read.split(",");
}
System.out.println(splited[0]);
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
}

Removing a line from a file via button action

YES, I have searched the method to remove a specific line via comparing&matching, but mine is different from the situations I've searched, and the wrong action takes place.
The code here is the actionPerformed for the button btnRemove. What it does is it removes the selected cell from the table, and also is meant to remove the corresponding cell (string) value from the file Activities.dat
However, what happens is that the code makes the entire file removed and blank, leaving 1 empty line, not just the line I want removed.
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
if (row >= 0) {
if (column >=0) {
for(int i=0; i<5; i++)
{
table.setValueAt("", row, column);
}
}
}
File file1 = new File("Activities.dat");
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter(file1));
BufferedReader reader = new BufferedReader(new FileReader(file1));
Object lineToRemove = table.getValueAt(row, column);
lineToRemove.toString();
System.out.print(lineToRemove);
String currentLine;
while((currentLine = reader.readLine()) != null)
{
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
Object lineToRemove = table.getValueAt(row, column);
lineToRemove.toString();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine);
}
writer.close();
}
catch (IOException ex)
{
Logger.getLogger(ActivityScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
You're making a duplicate lineToRemove in your while loop. It will also be better if you changed the type of line to String and assign the value of table.getValueAt(row, column).toString() to it (and don't change it afterwards). Also, you're setting the value of [row, column] before you get it. You will be searching for "" (searching for nothing if not a very good idea). Try doing something like this:
btnRemove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
if (row >= 0) {
if (column >= 0) {
File file1 = new File("Activities.dat");
File temp = new File(file1.getAbsolutePath() + ".tmp"); // temp file
PrintWriter writer = null;
BufferedReader reader = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(temp)), false);
reader = new BufferedReader(new FileReader(file1));
String lineToRemove = table.getValueAt(row, column).toString();
System.out.print(lineToRemove);
String currentLine;
while ((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.println(currentLine);
}
} catch (IOException ex) {
Logger.getLogger(ActivityScreen.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (reader != null)
reader.close();
if (writer != null) {
writer.flush();
writer.close();
file1.delete(); // delete the old one
temp.renameTo(file1); // make temp same as original
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
table.setValueAt("", row, column);
}
}
}
});
Look at RandomAccessFile. Leave the file as it is until the line you want to remove, then copy the rest of the file from the end of your removed part to the end of file from the point you started removing.
Pseudo code:
String line = "line I want to remove";
RandomAccessFile raf = openRandomAccessFile();
while(!line.equals(raf.readLine())) {
//just going to the point we want
}
long beginOfTheRemovingPointer = raf.getFilePointer()-size of removed line;
raf.seek(beginOfTheRemovingPointer);
raf.write(from beginOfTheRemovingPointer+size of removed line until the end);
raf.setLength(new length);
The RandomAccessFile methods exist. Just take a look at the API to know what they do exactly.

Categories

Resources