Populating and removing data from a txt.file - java

Hey I am working on a school project and am trying to code a questionbank. I am using a JFrame which allows the user to enter data. I then want to store data in a txt file so that I can later retrieve it. I am having trouble adding and deleting it to the questionbank tho. Any hints on how to delete a certain "question"?.
For Example if I want to Delete the maths question from the following file:
Geography_What is England's capital_Berlin_Manchester_Dover_London_D_3
Maths_What is 2+3_7_9_5_6_C_1
Economics_What is demand_idk_stuff_demand_supply_C_2
DELETE
String topic = Topic.getSelectedItem().toString();
String question = Question.getText();
String a = AnswerA.getText();
String b = AnswerB.getText();
String c = AnswerC.getText();
String d = AnswerD.getText();
String answer =Correct.getText();
String credit =Points.getText();
String remove = topic + "_" + question + "_" + a + "_" + b + "_" + c + "_" + d + "_" + answer + "_" + credit;
File inputFile = new File("Questions.txt");
File tempFile = new File("QuestionsTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = remove;
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
try {
writer.write(currentLine + System.getProperty("line.separator"));
} catch (IOException ex) {
Logger.getLogger(QuestionBank.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
inputFile.delete();
reader.close();
writer.close();
inputFile.delete();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
catch (IOException ex) {
ex.printStackTrace();
}
ADD
String topic = Topic.getSelectedItem().toString();
String question = Question.getText();
String a = AnswerA.getText();
String b = AnswerB.getText();
String c = AnswerC.getText();
String d = AnswerD.getText();
String answer =Correct.getText();
String credit =Points.getText();
String answerPos = "AaBbCcDd";
String scorePos = "12345";
try{
FileWriter writer = new FileWriter("Questions.txt", true);
writer.write(System.getProperty("line.separator"));
writer.write(topic);
writer.write("_");
writer.write(question);
writer.write("_");
writer.write(a);
writer.write("_");
writer.write(b);
writer.write("_");
writer.write(c);
writer.write("_");
writer.write(d);
writer.write("_");
writer.write(answer);
writer.write("_");
writer.write(credit);
writer.close();
JOptionPane.showMessageDialog(rootPane, "Success");
}
catch(HeadlessException | IOException e){
JOptionPane.showMessageDialog(rootPane, "Error");
}
}

I would suggest you to use a serialization library to save objects like Gson for example. Then you can manage saving and loading more easily. Or use a standard format like CSV or XML.

Related

Replace multiple string in a file java

I am trying to replace multiple strings in a file from source as ArrayList. But the application is erasing the old string before replacing a new one. Please help.
public static void writeNewFile(File template, ArrayList<String> data) {
File file = template;
String nameToReplace = "((name))";
String productToReplace = "((product))";
String giftToReplace = "((gift))";
String giftValueToReplace = "((gift-value))";
String outputFileName = data.get(0);
String workingDirectory = System.getProperty("user.dir");
Scanner scanner = null;
try {
scanner = new Scanner(file);
PrintWriter writer = new PrintWriter(workingDirectory + "\\Output\\" + outputFileName);
while (scanner.hasNextLine()) {
String line1 = scanner.nextLine();
writer.println(line1.replace(nameToReplace, data.get(1)));
writer.println(line1.replace(productToReplace, data.get(2)));
}
} catch (Exception e) {
System.out.println("Destination folder not found");
}
}
This worked for me
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String result = oldtext.replace(nameToReplace, data.get(1))
.replace(productToReplace, data.get(2))
.replace(giftToReplace, data.get(3));
// Write updated record to a file
FileWriter writer = new FileWriter(workingDirectory + "\\Output\\" + outputFileName);
writer.write(result);
writer.close();
} catch (IOException ioe) {
System.out.println("Write error");
}

Text modification in Java Netbeans

I'm trying to modify text in a file but instead of modifying it, it is just adding a new line with the new information:
Here's my code
String id= IDSearch.getText();
String newname = NameText.getText();
String newbarcode = BarcodeText.getText();
String newsupplier= SupplierText.getText();
String newamount1= AmountText.getText();
ArrayList<Item> ItemsList = new ArrayList<>();
if (id.isEmpty() || newname.isEmpty() || newbarcode.isEmpty() || newsupplier.isEmpty() || newamount1.isEmpty()) {
JOptionPane.showMessageDialog(this, " Please Fill all fields");}
else{
try {
File Items = new File ("Items.txt");
FileReader fr = new FileReader(Items);
BufferedReader br = new BufferedReader(fr);
String data;
Item tempItem;
while ((data = br.readLine()) != null) {
tempItem = new Item(data);
if (tempItem.getID().equals(IDSearch))
{
tempItem.setItemName(newname);
tempItem.setItemBarcode(newbarcode);
tempItem.setSupplierID(newsupplier);
tempItem.setAmount(newamount1);
}
ItemsList.add(tempItem);
}
try (PrintWriter pw = new PrintWriter(new FileWriter(Items, true))) {
ItemsList.forEach((item) -> {
pw.println(newname + ";" + newbarcode+ ";" + newsupplier + ";" + newamount1);
});
JOptionPane.showMessageDialog(this, "Student Updated Succesfully");
}
}catch (IOException ex) {
}
}
}
I can't seem to be able to update the tex file the way it was supposed to update. Any help would be much appreciated!
You have append set to true. Doing new FileWriter(Items, false) or just (new FileWriter(Items) should fix the issue.

Reading text file variables and updated assigned values

I have a text file which has text as follows:
emVersion = "1.32.4.0";
ecdbVersion = "1.8.9.6";
ReleaseVersion = "2.3.2.0";
I want to update the version number by taking the input from a user if user enter the new value for emVersion as 1.32.5.0 then
emVersion in text file will be updated as emVersion = "1.32.5.0";
All this I have to do using java code. What I have done till now is reading text file line by line then in that searching the word emVersion if found the broken line into words and then replace the token 1.32.4.0 but it is not working because spaces are unequal in the file.
Code what i have written is :
public class UpdateVariable {
public static void main(String s[]){
String replace = "1.5.6";
String UIreplace = "\""+replace+"\"";
File file =new File("C:\\Users\\310256803\\Downloads\\setup.rul");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("svEPDBVersion"))
{
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
String var_4 = tokens[3];
String OldVersion = var_3;
String NewVersion = UIreplace;
try{
String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
content = content.replaceAll(OldVersion, NewVersion);
IOUtils.write(content, new FileOutputStream(file), StandardCharsets.UTF_8);
} catch (IOException e) {
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//---this code changes each version's values but the is a option to keep the old value.
Scanner in = new Scanner(System.in);
File file = new File("versions.txt");
ArrayList<String> data = new ArrayList<>();
String[] arr =
{
"emVersion", "ecdbVersion", "releaseVersion"
};
String line = "";
String userInput = "";
try (BufferedReader br = new BufferedReader(new FileReader(file));)
{
while ((line = br.readLine()) != null)
{
data.add(line);
}
for (int i = 0; i < arr.length; i++)
{
System.out.println("Please enter new " + arr[i] + " number or (s) to keep the old value.");
userInput = in.nextLine();
line = data.get(i);
String version = line.substring(0, line.indexOf(" "));
if (arr[i].equalsIgnoreCase(version))
{
arr[i] = line.replace(line.subSequence(line.indexOf("= "), line.indexOf(";")), "= \"" + userInput + "\"");
}
if (userInput.equalsIgnoreCase("s"))
{
arr[i] = line;
}
}
PrintWriter printWriter = new PrintWriter(new FileWriter(file, false));
printWriter.println(arr[0]);
printWriter.println(arr[1]);
printWriter.println(arr[2]);
printWriter.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
Use regular expression eg:- line.trim().split("\s*=\s*"); . If it does not work please let me know , i will provide you complete solution.

How to write a drop down list to a file in webdriver/java?

I tried giving the string in the code, but I have a requirement where a txt file has to be added to java and from there read the text and compare it with the items in the array. In array we will have drop down list items.
Without using string in the txt, can I read the same string from the txt file and compare with array?
Here is the code:
driver.get("http://www.depreportingservices.state.pa.us/ReportServer/Pages/ReportViewer.aspx?%2fOil_Gas%2fOil_Gas_Well_Historical_Production_Report");
WebElement mSelectElement = driver.findElement(By.xpath("//select[#id='ReportViewerControl_ctl04_ctl03_ddValue']"));
List<WebElement> optionsList = mSelectElement.findElements(By.tagName("optio driver.get("http://www.depreportingservices.state.pa.us/ReportServer/Pages/ReportViewer.aspx?%2fOil_Gas%2fOil_Gas_Well_Historical_Production_Report");
WebElement mSelectElement = driver.findElement(By.xpath("//select[#id='ReportViewerControl_ctl04_ctl03_ddValue']"));
List<WebElement> optionsList = mSelectElement.findElements(By.tagName("option"));
Wait(20000);
String oldMonth = "E:\\Ashik\\wkspSelenium\\Stackcode\\Month";
String line = null;
String loc="E:\\Ashik\\wkspSelenium\\Stackcode\\Month";
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(oldMonth);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
for (int i = 2; i < optionsList.size(); i++) {
WebElement element = optionsList.get(i);
String newMonth = element.getText();
if (!oldMonth.equals("All") && !newMonth.equals("All")) {
if (newMonth.equals(oldMonth)) {
// IF the string are same, nthng we need to do
}
else if (!newMonth.equals(oldMonth)) {
/*
* If the string are not same,then i.e., considered as new Month, download the new month details*/
element.click();
driver.findElement(By.xpath(".//[#id='ReportViewerControl_ctl04_ctl00']")).click();
Wait(200000);
//Click on File save button
driver.findElement(By.xpath(".//*[#id='ReportViewerControl_ctl05_ctl04_ctl00_Button']")).click();
//wait time to load the options
Wait(20000);
driver.findElement(By.xpath(".//[#id='ReportViewerControl_ctl05_ctl04_ctl00_Menu']/div[2]/a")).click();
Wait(10000);
System.out.println( "New month data downloaded in csv format:==>"+newMonth);
break;
}
}
oldMonth = newMonth;
// String fstream=newMonth;
}
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + oldMonth + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + oldMonth + "'");
// Or we could just do this: ex.printStackTrace();
}
//fstream(fstream1);
FileWriter newMonth = new FileWriter(loc);
}

How to Update or delete a specific line from a .txt file?

I already have methods to insert data in to a text file and search. now I want methods for 'updating' and 'deleting' a selected record.
this is what I have done so far,
private void InsertbuttonActionPerformed(java.awt.event.ActionEvent evt) {
fileWriter = null;
try {
String phone = Phone.getText();
String fname = Fname.getText();
String lname = Lname.getText();
String nic = NIC.getText();
String city = City.getSelectedItem().toString();
fileWriter = new FileWriter(file, true);
fileWriter.append(phone + "|" + fname + "|" + lname + "|" + nic + "|" + city+ "|");
fileWriter.append("\r\n");
fileWriter.flush();
JOptionPane.showMessageDialog(InsertGUI.this, "<html> " + phone + " <br> Successfully saved! </html>");
Phone.setText(null);
NIC.setText(null);
Fname.setText(null);
Lname.setText(null);
City.setSelectedIndex(0);
} catch (IOException ex) {
Logger.getLogger(InsertGUI.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(InsertGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {
try {
fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
String selectedphone = SearchF.getText();
String content = "";
String temp = "";
try {
while ((temp = br.readLine()) != null) {
content += temp;
}
} catch (IOException ex) {
Logger.getLogger(UpdateGUI.class.getName()).log(Level.SEVERE, null, ex);
}
HashMap<String, String> map = new HashMap();
StringTokenizer stringTokenizer = new StringTokenizer(content, "|");
boolean found = false;
while (stringTokenizer.hasMoreTokens()) {
String phone = stringTokenizer.nextElement().toString();
String fname = stringTokenizer.nextElement().toString();
String lname = stringTokenizer.nextElement().toString();
String nic = stringTokenizer.nextElement().toString();
String city = stringTokenizer.nextElement().toString();
if (phone.equalsIgnoreCase(selectedphone)) {
Phone.setText(phone);
NIC.setText(nic);
Fname.setText(fname);
Lname.setText(lname);
switch (city) {
case "Ambalangoda":
City.setSelectedIndex(0);
break;
case "Ampara":
City.setSelectedIndex(1);
break;
case "Anuradhapura":
City.setSelectedIndex(2);
break;
case "Avissawella":
City.setSelectedIndex(3);
break;
case "Badulla":
City.setSelectedIndex(4);
break;
case "Balangoda":
City.setSelectedIndex(5);
break;
}
found = true;
}
}
if (!found) {
JOptionPane.showMessageDialog(UpdateGUI.this, "Phone number not found!");
Phone.setText(null);
NIC.setText(null);
Fname.setText(null);
Lname.setText(null);
City.setSelectedIndex(0);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(UpdateGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
can someone please help me with this?
I want methods for:
private void UpdatebuttonActionPerformed(java.awt.event.ActionEvent evt) {
}
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
Thanks in advance! :)
I give you an example that i found. In this example i will replace a string inside of a line. You can see that in my case im reading from a txt.
/******
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the String "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
String line;String input = "";
while ((line = file.readLine()) != null) input += line + '\n';
file.close();
System.out.println(input); // check that it's inputted right
// this if structure determines whether or not to replace "0" or "1"
if (Integer.parseInt(type) == 0) {
input = input.replace(replaceWith + "1", replaceWith + "0");
}
else if (Integer.parseInt(type) == 1) {
input = input.replace(replaceWith + "0", replaceWith + "1");
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input);
// write the new String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
public static void main(String[] args) {
replaceSelected("Do the dishes","1");
}
*/
Result:
Original:
Original Text File Content:
Do the dishes0
Feed the dog0
Cleaned my room1
Output:
Do the dishes0
Feed the dog0
Cleaned my room1
Do the dishes1
Feed the dog0
Cleaned my room1
Recent output:
Do the dishes1 (HAS BEEN CHANGED)
Feed the dog0
Cleaned my room1
Maybe this example helps for you.
Regards!
Read data to string. Use string.replace(forDelte,""). And then just rewrite to txt file.

Categories

Resources