Java getting id from csv file to combo box - java

I am have a program were there are two forms one for the consultant and for the customer. On the first form the user will enter the consultant details and his ID will be saved in a csv file and this works fine.
Consultant cons_save = new Consultant();
cons_save.setPersonfirstname(this.jTextField1.getText());
cons_save.setPersonlastname(this.jTextField2.getText());
cons_save.setPersonID(this.jTextField4.getText());
this.jTextField1.setText("");
this.jTextField2.setText("");
this.jTextField3.setText("");
cons_save.ConsultantID = cons_save.PersonID;
cons_save.setConsultantID(this.jTextField4.getText());
this.jTextField4.setText("");
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter("E:\\ryan_assignment_sit2\\ConsID\\consID.csv", true));
writer.append(cons_save.ConsultantID);
writer.append(",");
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
cons_save.savecons();
After the id is saved the Id is called out from the csv to an array and this works fine as well.
public CreateCustomer() {
initComponents();
ArrayList<String> ConsIDList = new ArrayList<String>();
String csvFileToRead = "E:\\ryan_assignment_sit2\\ConsID\\consID.csv"; // Reads the CSV File.
BufferedReader br = null; // Creates a buffer reader.
String line = "";
String splitBy = ","; // Reader Delimiter
try {
br = new BufferedReader(new FileReader(csvFileToRead)); // Buffer Reader with file name to read.
Scanner reader = new Scanner(System.in);
while ((line = br.readLine()) != null) { //While there is a line to read.
reader = new Scanner(line);
reader.useDelimiter(splitBy);
while (reader.hasNext()) { // While there is a next value (token).
ConsIDList.add(reader.next());
}
}
} catch (FileNotFoundException exception) { // Exception Handler if the File is not Found.
exception.printStackTrace();
} catch (IOException exception) { // Input/Output exception
exception.printStackTrace();
} finally {
if (br != null) {
try {
br.close(); // Close the Scanner.
} catch (IOException exception) {
exception.printStackTrace();
}
}
Vector<String> vectorData = new Vector<String>(ConsIDList);
DefaultComboBoxModel<String> comboBoxModel = new DefaultComboBoxModel<>(vectorData);
this.jComboBox1.setModel(comboBoxModel);
}
}
The array is working fine but the combo box is not getting populated with the arraylist.

Related

When append "true" in FileWriter, items delete from list

I’m trying to add an item to the list which is stored in a file. And I’m experiencing an odd behavior when I’m creating an instance of FileWriter to do so. If 'true' is passed to ‘appended’ parameter in the constructor (new BufferedWriter(new FileWriter(filename, true))), the item doesn’t get added to the list. If I do not pass a parameter, the item is added to the list, but each time it overwrites an existing one. Can anyone help me with this?
What I've tried:
-using FileOutputStream - result the same, always overwriting items.
-added Context.MODE_PRIVATE - result the same, always overwriting items.
-bw.append(convertTaskToGson(task));
private List<Task> fillListFromGson(FileInputStream imputeStream) {
BufferedReader bufferedReader = prepareReadingFromFile(imputeStream);
String receiveString;
List<Task> taskList = new ArrayList<>();
try {
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
String jsonNewObject = stringBuilder.toString();
Task task = gson.fromJson(jsonNewObject, Task.class);
taskList.add(task);
}
return taskList;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG_INTERNAL_FILE_ERROR, "cannot fill list from gson");
return null;
}
}
private boolean saveTaskToInternalStorage(Task task) {
BufferedWriter bw = null;
try {
File file = new File(AppClass.getApplication().getFilesDir(), filename);
bw = new BufferedWriter(new FileWriter(filename, true));
bw.write(convertTaskToGson(task));
bw.newLine();
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
return false;
} finally {
if (bw != null)
try {
bw.close();
return true;
} catch (IOException ioe2) {
return false;
}
} return true;
}
}
Expected result: new items to be added in the end of the file.
Rewrite this block code:
BufferedReader inputStream = new BufferedReader(new InputStreamReader(getFileInputStream(internalFileName)));
while ((receiveString = inputStream.readLine()) != null) {
Task task = gson.fromJson(receiveString, Task.class);
taskList.add(task);
}
My mistake was incorrect inclusion StringBuilder,
and it broken the display of file items. After reinstall app - BufferedWriter(new FileWriter(filename, true)) works perfect to add new items in my file. Very stupid(

Why is this not reading in?

I know I'm not doing something correctly. I know the file needs to be Serializable to read a text file.
I've got implements Serializable on the main class. But my readText and my writeText aren't converting.
Nothing is coming in when I read and when I write out the file is not text.
public static ArrayList<String> readText() {
ArrayList<String> read = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Reading serialized file",
FileDialog.LOAD);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File inFile = new File(dirPath + foName);
BufferedReader in = null;
ObjectInputStream OIS = null;
try {
in = new BufferedReader(new FileReader(inFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = null;
try {
line = in.readLine();
} catch (IOException e1) {
e1.printStackTrace();
while (line != null) {
try {
FileInputStream IS = new FileInputStream(inFile);
OIS = new ObjectInputStream(IS);
inFile = (File) OIS.readObject();
} catch (IOException io) {
io.printStackTrace();
System.out.println("An IO Exception occurred");
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace(); // great for debugging!
System.out.println("An IO Exception occurred");
} finally
{
try {
OIS.close();
} catch (Exception e) {
}
}
}
}
return read;
}
public static void writeText(ArrayList<String> file) {
ArrayList<String> write = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Saving customer file",
FileDialog.SAVE);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File outFile = new File(dirPath + foName);
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
for (int i = 0; i < write.size(); i++) {
String w = write.get(i);
out.println(file.toString());
}
}
catch (IOException io) {
System.out.println("An IO Exception occurred");
io.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
Nothing is coming in
You're never calling read.add(line) and you're attempting to read the file within an infinite loop inside of the catch block, which is only entered if you are not able to read the file.
Just use one try block, meaning try to open and read the file at once, otherwise, there's no reason to continue trying to read the file if it's not able to be opened
List<String> read = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(inFile)) {
String line = null;
while ((line = in.readLine()) != null) {
read.add(line); // need this
}
} catch (Exception e) {
e.printStackTrace();
}
return read;
Now, whatever you're doing with this serialized object stuff, that's completely separate, and it isn't the file or your main class that needs set to Serializable, it's whatever object you would have used a writeObject method on. However, you're reading and writing String objects, which are already Serializable.
when I write out the file is not text
Not sure what you mean by not text, but if you followed the above code, you'll get exactly what was in the initial file... Anyway, you do not need a write list variable.
You must use the individual lines of ArrayList<String> file parameter instead, but not file.toString()
for (String line:file) {
out.println(line);
}
out.close(); // always close your files and writers

Make text viewer read files faster in android

I have a simple text viewer class that opens text file and reads the strings. But the problem is, when the file is large >0.5Mb, opening takes quite a while. Is there a way to load small part first and then load all others or any other way to make this process faster ? Here is my code:
InputStream inputStream = null;
String str = "";
StringBuffer buf = new StringBuffer();
TextView txt = (TextView)findViewById(R.id.textView);
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
if (inputStream!=null) {
try {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
txt.setText(buf.toString());
}
}

read from csv, delete line based on first portion

In my app I am displaying the first portion of each line of the CSV in a JList, and when it is selected and a button is pressed (delete) I want it to remove that line from the file based on the first entry. I am trying the method where you have a temp file then write to it then rename it at the end but that isnt working out for some reason. Any ideas?
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Delete service
String selected = (String) jList1.getSelectedValue();
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = new File("/users/aak7133/desktop/temp.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(passwords));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
//String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line);
}
boolean successful = temp.renameTo(passwords);
} catch (Exception e) {
}
updateList();
clearFields();
}
The problem is actually caused by the open reader and writer. This should work:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
String selected = (String) jList1.getSelectedValue();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = File.createTempFile("temp", ".txt", new File("/users/aak7133/desktop/"));
reader = new BufferedReader(new FileReader(passwords));
writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
// String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line + "\n");
}
if (passwords.canWrite()) {
try {
reader.close();
reader = null;
} catch (IOException ignore) {}
try {
writer.close();
writer = null;
} catch (IOException ignore) {}
String path = passwords.getAbsolutePath();
passwords.delete();
boolean successful = temp.renameTo(new File(path));
System.out.println(successful);
}
} catch (Exception e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {}
}
if (writer != null) {
try {
writer.close();
} catch (IOException ignore) {}
}
}
updateList();
clearFields();
}
I figured out I needed to put passwords.delete() before temp.renameTo(passwords). This fixed the issue right away.

How can I read a text file in Android?

I want to read the text from a text file. In the code below, an exception occurs (that means it goes to the catch block). I put the text file in the application folder. Where should I put this text file (mani.txt) in order to read it correctly?
try
{
InputStream instream = openFileInput("E:\\test\\src\\com\\test\\mani.txt");
if (instream != null)
{
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line,line1 = "";
try
{
while ((line = buffreader.readLine()) != null)
line1+=line;
}catch (Exception e)
{
e.printStackTrace();
}
}
}
catch (Exception e)
{
String error="";
error=e.getMessage();
}
Try this :
I assume your text file is on sd card
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
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) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text.toString());
following links can also help you :
How can I read a text file from the SD card in Android?
How to read text file in Android?
Android read text raw resource file
If you want to read file from sd card. Then following code might be helpful for you.
StringBuilder text = new StringBuilder();
try {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"testFile.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.i("Test", "text : "+text+" : end");
text.append('\n');
} }
catch (IOException e) {
e.printStackTrace();
}
finally{
br.close();
}
TextView tv = (TextView)findViewById(R.id.amount);
tv.setText(text.toString()); ////Set the text to text view.
}
}
If you wan to read file from asset folder then
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
Or If you wan to read this file from res/raw foldery, where the file will be indexed and is accessible by an id in the R file:
InputStream is = getResources().openRawResource(R.raw.test);
Good example of reading text file from res/raw folder
Put your text file in Asset Folder...& read file form that folder...
see below reference links...
http://www.technotalkative.com/android-read-file-from-assets/
http://sree.cc/google/reading-text-file-from-assets-folder-in-android
Reading a simple text file
hope it will help...
Try this code
public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
String aBuffer = "";
try {
File myFile = new File(pathRoot + nameFile);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
}
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return aBuffer;
}
First you store your text file in to raw folder.
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2)
continue;
long id = addWord(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}
Shortest form for small text files (in Kotlin):
val reader = FileReader(path)
val txt = reader.readText()
reader.close()
Try this
try {
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
String s ="";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
while (line != null)
{
s = s + line;
s =s+"\n";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
tv.setText(""+s);
}

Categories

Resources