Text modification in Java Netbeans - java

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.

Related

Populating and removing data from a txt.file

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.

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");
}

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.

Java Code check fields in duplicate, when value change start again

I want to write small java program to read data file first field and add seqcution number
Input file:
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Output file should be:
robert,190 vikign,...,0
robert,2401 windy,...,1
robert,1555 oakbrook,...,2
michell,2524 sprint,...,0
michell,1245 oakbrrok,...,1
xyz,2455 xyz drive,....,0
Check first field when value change sequction number start back to 0 otherwise add sequction number by 1
here is my code:
public static void createseq(String str) {
try {
BufferedReader br = null;
BufferedWriter bfAllBWP = null;
File folderall = new File("Sort_Data_File_Out");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
br = new BufferedReader(new FileReader(file));
String bwp = "FinalDataFileOut\\" + str;
bfAllBWP = new BufferedWriter(new FileWriter(bwp));
String line;
line = br.readLine();
String[] actionID = line.split("\\|");
String fullname = actionID[0].trim();
int seq = 0;
String fullnameb;
while ((line = br.readLine()) != null) {
actionID = line.split("\\|");
fullnameb = actionID[0].trim();
if(fullname.equals(fullnameb)) {
seq++;
}
else {
System.out.println(line + "======" + seq + "\n");
seq = 0;
fullname = fullnameb;
}
System.out.println("dshgfsdj "+line + "======" + seq + "\n");
}
}
}
catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
The below code will fix the issue.I have updated the code if you face any pblm plz let me know :
Input :
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Code :
public static void createseq() {
try {
File file = new File("d:\\words.txt"); //Hardcoded file for testing locally
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<String,Integer> counter = new HashMap<String, Integer>();
String line;
while((line = br.readLine())!= null)
{
String[] actionID = line.split(",");
String firstName = actionID[0];
if(counter.containsKey(firstName))
{
counter.put(firstName, counter.get(firstName) + 1);
}
else
{
counter.put(firstName,0);
}
System.out.println(line+" "+counter.get(firstName));
}
br.close();
} catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
Ouput Come :
robert,190 vikign,... 0
robert,2401 windy,... 1
robert,1555 oakbrook,... 2
michell,2524 sprint,... 0
michell,1245 oakbrrok,... 1
xyz,2455 xyz drive,.... 0

How to find circular dependency of a string using Java

If I have 2 files say ABCD.txt and DEF.txt. I need to check if the String "ABCD" is present in DEF.txt and also the string "DEF" present in ABCD.txt and write the combination to a file.
Totally I have around 15000 files and each file contain nearly 50 - 3000 lines has to be searched. I wrote a piece of code, its working.. but it takes one hour to display the entire list...
Is any better way of performing this? Please suggest me.
public void findCyclicDependency(){
Hashtable<String, String> htFileNameList_1 = new Hashtable<String, String>();
Hashtable<String, String> htCyclicNameList = new Hashtable<String, String>();
FileWriter fwCyclicDepen = null;
PrintWriter outFile = null;
FileInputStream fstream = null;
FileInputStream fstream_1 = null;
DataInputStream in = null;
BufferedReader br = null;
DataInputStream in_1 = null;
BufferedReader br_1 = null;
String strSV_File_CK="";
boolean bFound = false;
File fileToSearch = null;
String strSVFileNameForComparison = "";
String strSVDependencyFileLine = "";
String strSVDFileLineExisting = "";
String strCyclicDependencyOut = "";
try {
File baseInputDirectory = new File(strInputPath);
List<File> baseInputDirListing = FileListing.getFileListing(baseInputDirectory);
// Printing out the filenames for the SodaSystem
for (File swPackage : baseInputDirListing)
{
if (swPackage.isDirectory() && swPackage.getName().endsWith("Plus")) {
List<File> currSwPackageFileListing = FileListing.getFileListing(swPackage);
System.out.println("\n swPackage File --> " + swPackage.getName() );
strCyclicDependencyOut = strOutputPath + "_"+ swPackage.getName() + "_CyclicDependency.xml";
System.out.println("\n strCyclicDependencyOut File --> " + strCyclicDependencyOut );
fwCyclicDepen = new FileWriter(strCyclicDependencyOut);
outFile = new PrintWriter(new BufferedWriter(fwCyclicDepen));
outFile.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
outFile.write("<CyclicDependencyFile>");
for (File DependentFile : currSwPackageFileListing) {
strSV_File_CK = DependentFile.getName().substring(0, (DependentFile.getName().length() - 4)).trim();
htFileNameList_1.put(strSV_File_CK.toUpperCase(),strSV_File_CK.toUpperCase());
}
for (File DependentFile : currSwPackageFileListing)
{
fstream = new FileInputStream(DependentFile);
// Get the object of DataInputStream
in = new DataInputStream(fstream);
br = new BufferedReader(new InputStreamReader(in));
strSVFileNameForComparison = DependentFile.getName().substring(0, (DependentFile.getName().length() - 4)).trim();
//Read File Line By Line
while ((strSVDependencyFileLine = br.readLine()) != null)
{
bFound = false;
if (strSVDependencyFileLine.toUpperCase().indexOf("INDICES") == -1)
{
//Check the current line matches any of the file name in software package folder
if (htFileNameList_1.contains(strSVDependencyFileLine.trim().toUpperCase())
&& strSVDependencyFileLine.compareTo(strSVFileNameForComparison) != 0)
{
bFound = true;
// Get the file to search
for (File searchFile : currSwPackageFileListing)
{
if((searchFile.getName().substring(0, (searchFile.getName().length() - 4)).trim()).equals(strSVDependencyFileLine))
{
fileToSearch = searchFile;
break;
}
}
// Read the file where the file name is found
fstream_1 = new FileInputStream(fileToSearch);
in_1 = new DataInputStream(fstream_1);
br_1 = new BufferedReader(new InputStreamReader(in_1));
while ((strSVDFileLineExisting = br_1.readLine()) != null)
{
if (strSVDFileLineExisting.toUpperCase().indexOf("EXTRA") == -1)
{
if (htFileNameList_1.contains(strSVDFileLineExisting.trim().toUpperCase()) && bFound
&& strSVDFileLineExisting.compareTo(strSVDependencyFileLine) != 0
&& strSVDFileLineExisting.compareTo(strSVFileNameForComparison) == 0 )
{
if(!htCyclicNameList.containsKey(strSVDependencyFileLine) &&
!htCyclicNameList.containsValue(strSVDFileLineExisting))
{
htCyclicNameList.put(strSVDFileLineExisting,strSVDependencyFileLine);
outFile.write("<CyclicDepedency FileName = \"" + strSVDFileLineExisting + "\""+ " CyclicFileName = \"" +
strSVDependencyFileLine + "\" />");
break;
}
}
}
}
}
}
else
{
bFound = false;
}
}//if current line <>
}// reach each line in the current file
outFile.write("</CyclicDependencyFile>");
}
outFile.flush();
outFile.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}
Thanks
Ramm
There are several problems with your design. The most important one is repeated scanning of the file system. Try the code below.
static public void findCyclicDependency2() {
PrintWriter outFile = null;
Map<String,File> fileNames = new HashMap<String,File>();
Map<String,Set<String>> fileBackward = new HashMap<String,Set<String>>();
Map<String,Set<String>> fileForward = new HashMap<String,Set<String>>();
try {
File baseInputDirectory = new File(strInputPath);
List<File> baseInputDirListing = getFileListing(baseInputDirectory);
// Printing out the filenames for the SodaSystem
for(File swPackage:baseInputDirListing) {
if (! (swPackage.isDirectory()
|| swPackage.getName().endsWith("Plus"))) continue;
System.out.println("Loading file names");
List<File> currSwPackageFileListing = getFileListing(swPackage);
for(File dependentFile:currSwPackageFileListing) {
String name = trimName(dependentFile);
fileNames.put(name,dependentFile);
BufferedReader br = new BufferedReader(new FileReader(dependentFile));
String line;
Set<String> contFor = new HashSet<String>();
Set<String> contBack = new HashSet<String>();
while( (line=br.readLine()) != null ) {
line = line.toUpperCase().trim();
if( line.equals("EXTRA") ) continue;
if( line.equals("INDICES") ) continue;
if( line.equals(name) ) continue;
if( line.compareTo(name) == 1 ) {
contFor.add(line);
} else {
contBack.add(line);
}
}
fileBackward.put(name,contBack);
fileForward.put(name,contFor);
}
String strCyclicDependencyOut = strOutputPath + "_"
+ swPackage.getName() + "_CyclicDependency.xml";
outFile = new PrintWriter(new BufferedWriter(new FileWriter(strCyclicDependencyOut)));
outFile.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
outFile.write("<CyclicDependencyFile>");
for(Entry<String,Set<String>> entry : fileForward.entrySet()) {
String curr = entry.getKey();
for(String other : entry.getValue()) {
Set<String> otherRefs = fileBackward.get(other);
if( otherRefs == null ) continue;
if( otherRefs.contains(curr) ) {
outFile.write("<CyclicDepedency FileName = \""
+ fileNames.get(curr).getPath()
+ "\""
+ " CyclicFileName = \""
+ fileNames.get(other).getPath()
+ "\" />");
}
}
}
outFile.write("</CyclicDependencyFile>");
outFile.flush();
outFile.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Lucene comes to my mind.
Maybe it's more efficient to index all files, then query for the file names and use the results to detect your circular dependencies.

Categories

Resources