public void saveRecords() { // String server = jServer.getSelectedItem().toString(); String line, input = ""; String ln = System.getProperty("line.separator"); String dbList = jDBList.getText().replaceAll("\n", ln); boolean recordExist = false; File dbFile = new File("database.txt"); // Rewrite the existing file if (dbFile.exists()) { // JOptionPane.showMessageDialog(null, dbFile.getName()); // Check whether old records exist try { BufferedReader file = new BufferedReader(new FileReader("database.txt")); try { while ((line = file.readLine()) != null) { // if (line.equals("AWS")) { // input += line + '\n'; // while ((line = file.readLine()) != null && // !line.equals("-1")) input += line + '\n'; // content that needed to be update recordExist = true; // } else { // other += line + '\n'; // unchanged content // } } if (recordExist) { // records exist // input = server + "\n" + dbList + "\n-1\n"; input = dbList; input = input.replaceAll("\n", ln); // other = other.replaceAll("\n", ln); FileOutputStream File = new FileOutputStream("database.txt"); // File.write((input + other).getBytes()); File.write(input.getBytes()); } else { // no relevent records try { JOptionPane.showMessageDialog(null, dbList); BufferedWriter output = new BufferedWriter(new FileWriter(dbFile, true)); // output.append(server + "\n"); output.append(dbList); // output.append("-1"); output.close(); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "File could not be found!"); // insert code to run when exception occurs } } } catch (IOException e) { // To do } } catch (FileNotFoundException ex) { // To do } // Create a new file } else { try { // JOptionPane.showMessageDialog(null, "2"); dbFile.createNewFile(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Fail to create a file"); } // Output to the new file try { JOptionPane.showMessageDialog(null, dbList); PrintWriter printWriter = new PrintWriter(dbFile); // printWriter.println (server); // First line printWriter.println(dbList); // printWriter.println ("-1"); // Last line printWriter.close(); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "File could not be found!"); // insert code to run when exception occurs } } // dbFile.getParentFile().mkdirs(); if (flag == true) // go back to log in window L.loadDBList(); dispose(); }