I'm having trouble using the Java JFileChooser and was wondering if anyone could help me out. It's probably something really simple but I just can't spot what's wrong.
The JFileChooser window opens fine when I click my import button and I can navigate to any field but I just cant read them into my JTextFields.
Heres my JFileChooser method:
public void importFile() {
JFileChooser chooser = new JFileChooser();//A
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { //a
try {
BufferedReader file_in = new BufferedReader(
new FileReader(chooser.getSelectedFile().getPath()));
int i = 0;
String name = "",hnumber = "", mnumber = "", address = "";
while (((fileLines = file_in.readLine()) != null)) {
if (fileLines.length() > 0) {
i++;
if (i == 1) {
name = fileLines;
} else if (i == 2) {
hnumber = fileLines;
} else if (i == 3) {
mnumber = fileLines;
} else if (i == 4) {
address = fileLines;
String[] nameArray = name.split(" ");
Contact c = new Contact (nameArray[1], nameArray[0],
hnumber, mnumber, address);
contactList.add(c);
index = 0;
}
}
}
for (int j = 0; j < contactList.size(); j++) {
System.out.print(contactList.get(j).getname());
System.out.print(" ");
System.out.println(contactList.get(j).getmnumber());
System.out.println(contactList.get(j).gethnumber());
System.out.println(contactList.get(j).getaddress());
System.out.println(contactList.get(j).getsurname());
System.out.println(" ");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
You should use a List or a StringBuilder for ease of getting the lines. And do you get any error(s) as result? Debugging would really help to see where your program is breaking.
Here is something I put together for you real quick:
public void importFile() {
JFileChooser chooser = new JFileChooser();//A
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { //a
try {
FileReader fr = new FileReader(chooser.getSelectedFile().getPath());
BufferedReader file_in = new BufferedReader(fr);
List lines = new List();
String line = new String("");
while ((line = file_in.readLine()) != null) {
list.add(line);
if (list.size() >= 3) {
String[] nameArray = ((String)list.get(0)).split(" ");
Contact c = new Contact (nameArray[1], nameArray[0],
(String)list.get(1), (String)list.get(2),
(String)list.get(3));
contactList.add(c);
}
System.out.println(list.get(list.size()-1)); // Debug
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
I didn't compile it so may have some typos or of such...
It imports into a array list called "contactList" which you can see is on the 5th line from the bottom. So it doesn't go straight into the JTextFields but either way I can't get it to work.
Related
I am able to convert my csv file into an arraylist, but I want to be able to find the mean and standard deviation of each row in my arraylist. I would like to do this by converting each row to an individual array to be able to call for future use.
BufferedReader gradeBuffer = null;
try {
String gradeLine;
gradeBuffer = new BufferedReader(new FileReader("Assignment4-datafile.csv"));
// Read in file line by line
while ((gradeLine = gradeBuffer.readLine()) != null) {
System.out.println(gradeCSVtoArrayList(gradeLine));
}
//throw exception if file not found
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (gradeBuffer != null) gradeBuffer.close();
} catch (IOException gradeException) {
gradeException.printStackTrace();
}
}
}
// Convert CSV to ArrayList using Split
public static ArrayList<String> gradeCSVtoArrayList(String gradeCSV) {
ArrayList<String> gradeResult = new ArrayList<String>();
if (gradeCSV != null) {
String[] splitData = gradeCSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
gradeResult.add(splitData[i].trim());
}
}
}
return gradeResult;
}
}
I think the first thing that you need to do is change gradeCSVtoArrayList to return a List of numbers, either Long or Double depending on if it is integer or floating point numbers.
public static ArrayList<Long> gradeCSVtoArrayList(String gradeCSV) {
ArrayList<Long> gradeResult = new ArrayList<Long>();
if (gradeCSV != null) {
String[] splitData = gradeCSV.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
gradeResult.add(Long.parseLong(splitData[i].trim()));
}
}
}
return gradeResult;
}
WIth this list you can find mean and standard deviation.
I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I am currently working on an add-on to a rhythm game called osu! using Java. There are multiple windows involved, but after the actionPerformed event listener is invoked for one of them, it creates another window that creates an object the constructor of which calls two methods that each use a BufferedReader. However, once I click the button for the actionPerformed, the program hangs and freezes until it is terminated from task manager. Here is the actionPerformed code for the GUI window:
private void btnCreateActionPerformed(ActionEvent evt) throws IOException {
String text = textBeats.getText();
if (text == null) {
JOptionPane.showMessageDialog(contentPane, "Please enter a positive number.");
}
boolean isNumber = true;
for (char c : text.toCharArray()) {
if (!Character.isDigit(c)) {
isNumber = false;
} else if (c == '-') {
isNumber = false;
}
}
if (isNumber) {
double beats = Double.parseDouble(text);
WindowCode window = new WindowCode(drawArea, file, beats);
window.setVisible(true);
this.dispose();
} else {
JOptionPane.showMessageDialog(contentPane, "Please enter a positive number.");
}
}
And here are the two methods called when creating WindowCode:
public double[] getLastTimingPoint() {
String line;
String timings[] = new String[8];
double pointElements[] = new double[8];
boolean isTiming = false;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(osuFile), "UTF-8"))){
while ((line = reader.readLine()) != null) {
if (line.contains("[TimingPoints]")) {
isTiming = true;
} else if (line.contains("[Colours]") || line.contains("[HitObjects]")) {
isTiming = false;
}
if (isTiming) {
if (!line.contains("[TimingPoints]") && !line.contains("[Colours]") && !line.contains("[HitObjects]") && line.length() > 0) {
timings = line.split(",");
}
}
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < timings.length; i++) {
pointElements[i] = Double.parseDouble(timings[i]);
}
System.out.println("1");
return pointElements;
}
public double[] getLastInheritedPoint() {
String line;
String timings[] = new String[8];
double pointElements[] = new double[8];
boolean isTiming = false;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(osuFile), "UTF-8"))) {
while ((line = reader.readLine()) != null) {
if (line.contains("[TimingPoints]")) {
isTiming = true;
}
while (isTiming) {
if (!line.contains("[TimingPoints]") && !line.contains("[Colours]") && !line.contains("-")) {
timings = line.split(",");
}
}
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < timings.length; i++) {
pointElements[i] = Double.parseDouble(timings[i]);
}
System.out.println("2");
return pointElements;
}
I have tried to print out checkpoint numbers and it only prints "1" to the console, leading me to believe that it is the second method that is causing this. My question is if the BufferedReader affects the EDT somehow and if it does, how I should get around it.
On the second method you have this inner loop:
while (isTiming) {
if (!line.contains("[TimingPoints]") && !line.contains("[Colours]") && !line.contains("-")) {
timings = line.split(",");
}
}
If the file being read contains this string "[TimingPoints]" then variable isTiming will be set to true, and no one else resets it back to false, being trapped into an infinite loop.
You should revise that loop logic.
I know my code is not optimal and there is certainly a better way to write what I am trying to do than how I have it written.
I am trying to setup a reader so that it inserts information into an array list. Right now my problem is that I cannot find out how to add an object to an array list only once. The last object of the file is filling the empty spaces of the arrayList.
public void readCharacterFile() {
String fileName = "C:/Users/brenton.reittinger/Desktop/characters.txt";
String line = null;
String fileContent = "";
try {
FileReader in = new FileReader(fileName);
BufferedReader bufferReader = new BufferedReader(in);
while((line = bufferReader.readLine()) != null) {
fileContent = fileContent + line;
}
bufferReader.close();
} catch(Exception e){
e.printStackTrace();
}
Character character = new Character();
Attributes attribute = new Attributes();
character.setAttribute(attribute);
String[] file = fileContent.split(":");
int count = 0;
for (String fileSection : file) {
if (fileSection.length() > 0) {
if(count == 5) {
character.getAttribute().setLevel(Integer.parseInt(fileSection));
count++;
}
if(count == 4) {
character.getAttribute().setExperience(Integer.parseInt(fileSection));
count++;
}
if(count == 3) {
character.getAttribute().setHealth(Integer.parseInt(fileSection));
count++;
}
if(count == 2) {
character.getAttribute().setAttack(Integer.parseInt(fileSection));
count++;
}
if(count == 1) {
character.setRace(fileSection);
count++;
}
if(count == 0) {
character.setName(fileSection);
count++;
}
}
}
user.addCharacterToList(character);
}
Why not using a java Set instead? Sets guarantee that each object instance can only occur once.
any way easier to do this??
i'm trying to import a file which is four lines:
name
phone
mobile
address
I'm using:
public void importContacts() {
try {
BufferedReader infoReader = new BufferedReader(new FileReader(
"../files/example.txt"));
int i = 0;
String loadContacts;
while ((loadContacts = infoReader.readLine()) != null) {
temp.add(loadContacts);
i++;
}
int a = 0;
int b = 0;
for (a = 0, b = 0; a < temp.size(); a++, b++) {
if (b == 4) {
b = 0;
}
if (b == 0) {
Name.add(temp.get(a));
}
if (b == 1) {
Phone.add(temp.get(a));
}
if (b == 2) {
Mobile.add(temp.get(a));
}
if (b == 3) {
Address.add(temp.get(a));
}
}
}
catch (IOException ioe) {
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
txtName.setText(Name.get(index));
txtPhone.setText(Phone.get(index));
txtMobile.setText(Mobile.get(index));
txtAddress.setText(Address.get(index));
}
is their an easier way? looks long winded!
You can use the Scanner Class.
Scanner s = new Scanner(new File("input.txt"));
name = s.nextLine();
phone = s.nextLine();
mobile = s.nextLine();
address = s.nextLine();
Apache Fileutils readFileToString() or readLines() makes the code more clean.
import org.apache.commons.io.FileUtils;
...
File file = new File("foobar.txt");
try
{
List<String> data = FileUtils.readLines(file);
// Iterate the result to print each line of the file.
Iterator<String> iter = data.iterator();
while(iter.hasNext()) {
Name.add(iter.next());
if (iter.hasNext()) {
Phone.add(iter.next());
}
if (iter.hasNext()) {
Mobile.add(iter.next());
}
if (iter.hasNext()) {
Address.add(iter.next());
}
}
} catch (IOException e)
{
e.printStackTrace();
}
You could even make it a bit shorter by using a construction like
if (iter.hasNext()) Phone.add(iter.next());
but personally I feel that discarding braces makes code more error-prone. You could put it on one line, though.
Create a data object representing your set of data. With the new object, take in a string and parse it locally in the new object.
Driver Class:
readInFromFile
EntityClass
EntityClass(String) < calls the parse method
get[data elements]
parseFromString(String info) <- this is responsible for all of your reading
The "readFromFile" method will turn into:
....
while ((String line= reader.readLine) != null) {
list.add(new Entity(line));
}
BufferedReader infoReader = new BufferedReader(new FileReader("../files/example.txt"));
String loadContacts;
List<People> list = new ArrayList<People>();
while ((loadContacts = infoReader.readLine()) != null) {
String[] singleContact = loadContacts.split(REGEXP_FOR_SPLIT_VALUES);
People p = new People();
p.setName(singleContact[0]);
p.setPhone(singleContact[1]);
p.setMobile(singleContact[2]);
p.setAddress(singleContact[3]);
list.add(p);
}
How about this?
while(infoReader.hasNext()) {
Name.add(infoReader.readLine());
Phone.add(infoReader.readLine());
Mobile.add(infoReader.readLine());
Address.add(infoReader.readLine());
}
although I'd prefer changing the Name, Phone etc classes to be one class representing one contact.
Here's how I would do it, using the new Scanner class to read easily and take care of IOExceptions, using the ClassLoader to find the file, and using a simple #Data class to store the data.
public void importContacts() {
Scanner scanner = new Scanner(ClassLoader.getSystemClassLoader().getResourceAsStream("example.txt"));
List<Contact> list = Lists.newArrayList();
while(scanner.hasNext()) {
list.add(new Contact(
scanner.nextLine(),
scanner.nextLine(),
scanner.nextLine(),
scanner.nextLine()
));
}
Contact c = list.get(index);
txtName.setText(c.getName());
txtAddress.setText(c.getAddress());
txtPhone.setText(c.getPhone());
txtMobile.setText(c.getMobile());
}
private static #Data class Contact {
private final String name, phone, mobile, address;
}
If the file will only ever contain one contact and you have control over the format of the source text file you could reformat it like a properties file:
name=value
Then you'd read it in as a properties file (see ResourceBundle), which ends up being simple:
Mobile.add(properties.getProperty("mobile"))
Why not just:
public String readLine(BufferedReader pReader) {
try {
return pReader.readLine();
} catch(IOException IOE) {
/* Not a very good practice but let say "We don't care!" */
// Return null if the line is not there (like there was no 4 lines in the file)
return null;
}
}
public void importContacts() {
try {
BufferedReader infoReader = new BufferedReader(new FileReader("../files/example.txt"));
txtName .setText(readLine(infoReader));
txtPhone .setText(readLine(infoReader));
txtMobile .setText(readLine(infoReader));
txtAddress.setText(readLine(infoReader));
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
}
Hope this helps.