Read and Write File data

Here i am writing how to read the content of a file and how to write content to a file and how to extract and modify the file data with some optimization formulas like updating fields for the particular user ,updating info for all existing users .

I have been asked to do this task (Standalone application) .So without using DB i came up with a solution with help of SWING in particular J Frame,JTextfeild.

Operations have been done so far:

  • Read data from a file
  • Write data to a file
  • Append data to a existing file
  • Update All data like replace “name” as “username” for all entries
  • Update individual data attributes like Password,Hobbies for a Particular user.
  • Bulk update/insert/delete

Useful Links:

Link1 Link2 Link3

Here are my .java files:

Bean.java

package com.lmig.classes;

public class Bean {
private String username;
private String password;
private String address;
public Bean(String username, String password, String address, String hobbies) {
super();
this.username = username;
this.password = password;
this.address = address;
this.hobbies = hobbies;
}
private String hobbies;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getHobbies() {
return hobbies;
}
public void setHobbies(String hobbies) {
this.hobbies = hobbies;
}
}

 

OpenClose.java

package com.lmig.classes;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class OpenClose extends JFrame {
static String savedPathByUser = null, targetLoadPath = null, stringPath = null;
static String changepath2, string1, string2, string3, string4;
static String oldString, newString, propertyName, userNameUnique;
static String alloldString, allnewString;
public static boolean choosefileBool = false;
private JTextField filename = new JTextField(), directoryName = new JTextField();
private JButton inputFile = new JButton(“Input File”), outputFile = new JButton(“Output File”),
replaceAll = new JButton(“ReplaceAll”),replaceAllOutput = new JButton(“ReplaceAll Output”), enetrValuesIP = new JButton(“Give Input Values”),
viewOutputData = new JButton(“View Output Data”);

public OpenClose() {
JPanel pJPanel = new JPanel();
inputFile.addActionListener(new InputIMPL());
pJPanel.add(inputFile);
outputFile.addActionListener(new OutputIMPL());
pJPanel.add(outputFile);
replaceAll.addActionListener(new ReplaceAllIMPL());
pJPanel.add(replaceAll);
replaceAllOutput.addActionListener(new ReplaceAllOutputIMPL());
pJPanel.add(replaceAllOutput);
enetrValuesIP.addActionListener(new EnterIPIMPL());
pJPanel.add(enetrValuesIP);
viewOutputData.addActionListener(new ViewIMPL());
pJPanel.add(viewOutputData);
Container cp = getContentPane();
cp.add(pJPanel, BorderLayout.SOUTH);
directoryName.setEditable(false);
filename.setEditable(false);
pJPanel = new JPanel();
pJPanel.setLayout(new GridLayout(2, 2));
pJPanel.add(filename);
pJPanel.add(directoryName);
cp.add(pJPanel, BorderLayout.NORTH);
}

class ViewIMPL implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
PropertyOperations.mechangelogic(oldString, newString, propertyName, userNameUnique, changepath2);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

class EnterIPIMPL implements ActionListener {
public void actionPerformed(ActionEvent e) {
SpecificFeildChange swingControlDemo = new SpecificFeildChange();
swingControlDemo.showTextFieldDemo();
}
}

class ReplaceAllOutputIMPL implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
File file = new File(stringPath);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = “”, oldtext = “”;
while ((line = reader.readLine()) != null) {
oldtext += line + “\r\n”;
}
reader.close();
String newtext = oldtext.replaceAll(OpenClose.alloldString, OpenClose.allnewString);
System.out.println(OpenClose.savedPathByUser + “.txt”);
changepath2 = OpenClose.savedPathByUser + “2.txt”;
FileWriter writer = new FileWriter(OpenClose.savedPathByUser + “.txt”);
writer.write(newtext);
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
class ReplaceAllIMPL implements ActionListener {
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
String[] columns = null;
boolean loadB = loadProperties();
if (loadB) {
columns = new String[ReadProperties.hashMapAttributes.size()];
for (int i = 1; i <=ReadProperties.hashMapAttributes.size(); i++) {
columns[i – 1] = ReadProperties.hashMapAttributes.get(“key” + i);
}
}
OldtoNewStringChange changeObject = new OldtoNewStringChange();
changeObject.showTextField();
}
}

class InputIMPL implements ActionListener {
public void actionPerformed(ActionEvent e) {
boolean loadB = loadProperties();
if (loadB) {
JFileChooser c = new JFileChooser();
int rVal = c.showOpenDialog(OpenClose.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(c.getSelectedFile().getName());
directoryName.setText(c.getCurrentDirectory().toString());
stringPath = “/” + c.getCurrentDirectory() + “/” + c.getSelectedFile().getName() + “/”;
targetLoadPath = c.getCurrentDirectory().toString() + “/” + c.getSelectedFile().getName();
choosefileBool = true;
}
if (rVal == JFileChooser.CANCEL_OPTION) {
filename.setText(“cancelled”);
directoryName.setText(“”);
}
} else {
System.out.println(“Error..Please load properties file”);
}
}

}

private boolean loadProperties() {
ReadProperties.loadProperties();
if (ReadProperties.hashMapAttributes.isEmpty()) {
return false;
} else {
return true;
}
}

class OutputIMPL implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser c = new JFileChooser();
int rVal = c.showSaveDialog(OpenClose.this);
if (rVal == JFileChooser.APPROVE_OPTION) {
filename.setText(c.getSelectedFile().getName());
directoryName.setText(c.getCurrentDirectory().toString());
}
if (rVal == JFileChooser.CANCEL_OPTION) {
filename.setText(“You pressed cancel”);
directoryName.setText(“”);
}
savedPathByUser = c.getCurrentDirectory().toString() + “\\” + c.getSelectedFile().getName();
}
}

public static void main(String[] args) {
setDimenisions(new OpenClose(), 750, 550);
}

public static void setDimenisions(JFrame frame, int width, int height) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
}

 

PropertyOperations.java

 

package com.lmig.classes;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class PropertyOperations extends JFrame {
public static void mechangelogic(String pstring1, String pstring2, String pstring3, String pstring4,
String changepath2) throws IOException {
int firstPropLen = 0, secondPropLen = 0, thirdPropLen = 0, forthPropLen = 0;
int firstTemp, secondTemp, thirdTemp, forthTemp;
String scannerLine, scannerPropValue1 = null, scannerPropValue2 = null, scannerPropValue3 = null,
scannerPropValue4 = null;
Scanner scanner = null;
if (OpenClose.choosefileBool) {
scanner = new Scanner(new FileReader(OpenClose.targetLoadPath));
} else {
System.out.println(“Error ..Please choose I/P file”);
}
Bean bean;
Map<String, Bean> personMap = new HashMap<>();
String name = “entry”;
int tempIncrement = 0;
if (ReadProperties.loadBooleanvalue) {
if (ReadProperties.hashMapAttributes.size() != 0) {
firstPropLen = ReadProperties.hashMapAttributes.get(“key1”).length();
secondPropLen = ReadProperties.hashMapAttributes.get(“key2”).length();
thirdPropLen = ReadProperties.hashMapAttributes.get(“key3”).length();
forthPropLen = ReadProperties.hashMapAttributes.get(“key4”).length();
}
} else {
System.out.println(“Error..While loading “);
}
while (scanner.hasNext()) {
tempIncrement++;
scannerLine = scanner.nextLine();
firstTemp = scannerLine.indexOf(ReadProperties.hashMapAttributes.get(“key1”));
secondTemp = scannerLine.indexOf(ReadProperties.hashMapAttributes.get(“key2”));
thirdTemp = scannerLine.indexOf(ReadProperties.hashMapAttributes.get(“key3”));
forthTemp = scannerLine.indexOf(ReadProperties.hashMapAttributes.get(“key4”));
System.out.println(firstTemp);
System.out.println(firstPropLen);
scannerPropValue1 = scannerLine.substring(firstTemp + firstPropLen, secondTemp);
scannerPropValue2 = scannerLine.substring(secondTemp + secondPropLen, thirdTemp);
scannerPropValue3 = scannerLine.substring(thirdTemp + thirdPropLen, forthTemp);
scannerPropValue4 = scannerLine.substring(forthTemp + forthPropLen, scannerLine.length() – 1);
bean = new Bean(scannerPropValue1, scannerPropValue2, scannerPropValue3, scannerPropValue4);
personMap.put(name + tempIncrement, bean);
if (changepath2 == null) {
changepath2 = OpenClose.savedPathByUser + “2”;
}
FileWriter writer = new FileWriter(changepath2);
for (String key : personMap.keySet()) {
try {
if (“username”.equalsIgnoreCase(pstring3)
&& personMap.get(key).getUsername().trim().equalsIgnoreCase(pstring1)
&& personMap.get(key).getUsername().trim().equalsIgnoreCase(pstring4)) {
Files.write(Paths.get(changepath2), pstring2.getBytes(), StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getPassword().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getAddress().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getHobbies().getBytes(),
StandardOpenOption.APPEND);
} else if (“password”.equalsIgnoreCase(pstring3)
&& personMap.get(key).getPassword().trim().equalsIgnoreCase(pstring1)
&& personMap.get(key).getUsername().trim().equalsIgnoreCase(pstring4)) {
System.out.println(true);
Files.write(Paths.get(changepath2), personMap.get(key).getUsername().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), pstring2.getBytes(), StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getAddress().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getHobbies().getBytes(),
StandardOpenOption.APPEND);
} else if (“address”.equalsIgnoreCase(pstring3)
&& personMap.get(key).getAddress().trim().equalsIgnoreCase(pstring1)
&& personMap.get(key).getUsername().trim().equalsIgnoreCase(pstring4)) {
Files.write(Paths.get(changepath2), personMap.get(key).getUsername().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getPassword().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), pstring2.getBytes(), StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getHobbies().getBytes(),
StandardOpenOption.APPEND);
} else if (“hobbies”.equalsIgnoreCase(pstring3)
&& personMap.get(key).getHobbies().trim().equalsIgnoreCase(pstring1)
&& personMap.get(key).getUsername().trim().equalsIgnoreCase(pstring4)) {
Files.write(Paths.get(changepath2), personMap.get(key).getUsername().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getPassword().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getAddress().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), pstring2.getBytes(), StandardOpenOption.APPEND);
} else {
Files.write(Paths.get(changepath2), personMap.get(key).getUsername().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getPassword().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getAddress().getBytes(),
StandardOpenOption.APPEND);
Files.write(Paths.get(changepath2), personMap.get(key).getHobbies().getBytes(),
StandardOpenOption.APPEND);
}

} catch (IOException e) {
}
}
}
}
}

 

OldtoNewChangeString.java

 

package com.lmig.classes;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class OldtoNewStringChange {
static String olds = null, news = null, chgid = null;
static String oldString, newString;
static String[] values;
static boolean b = false;
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;

public OldtoNewStringChange() {
prepareGUI();
}

public static void main(String[] args) {
OldtoNewStringChange object = new OldtoNewStringChange();
object.showTextField();
}

private void prepareGUI() {
mainFrame = new JFrame();
mainFrame.setSize(500, 400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel(“”, JLabel.CENTER);
statusLabel = new JLabel(“”, JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

void showTextField() {
JLabel oldStringLable = new JLabel(“old String”, JLabel.RIGHT);
JLabel newStringLable = new JLabel(“new String: “, JLabel.RIGHT);
final JTextField oldText = new JTextField(6);
final JTextField newText = new JTextField(6);

JButton changeButton = new JButton(“Change All”);
changeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = “old is ” + oldText.getText();
data += “, new is: ” + new String(newText.getText());
OpenClose.alloldString = oldText.getText();
OpenClose.allnewString = newText.getText();
System.out.println(OpenClose.alloldString);
System.out.println(OpenClose.allnewString);
OldtoNewStringChange.b = true;
mainFrame.dispose();
}
});

controlPanel.add(oldStringLable);
controlPanel.add(oldText);
controlPanel.add(newStringLable);
controlPanel.add(newText);
controlPanel.add(changeButton);
mainFrame.setVisible(true);
}
}

 

SpecifiedFeildChange.java

 

package com.lmig.classes;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SpecificFeildChange {
static String olds = null, news = null, chgid = null;
static String string1, string2, string3;
static String[] values;
static boolean b = false;
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;

public SpecificFeildChange() {
prepareGUI();
}

public static void main(String[] args) {
SpecificFeildChange swingControlDemo = new SpecificFeildChange();
swingControlDemo.showTextFieldDemo();
}

private void prepareGUI() {
mainFrame = new JFrame(“Java Swing Examples”);
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel(“”, JLabel.CENTER);
statusLabel = new JLabel(“”, JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

void showTextFieldDemo() {
JLabel oldStringlabel = new JLabel(“old String”, JLabel.RIGHT);
JLabel newStringLabel = new JLabel(“new String: “, JLabel.LEFT);
JLabel propertyLabel = new JLabel(“Proprty”, JLabel.RIGHT);
JLabel usernameLabel = new JLabel(“Username”, JLabel.CENTER);
final JTextField oldStringTxt = new JTextField(6);
final JTextField newStringTxt = new JTextField(6);
final JTextField propertyTxt = new JTextField(6);
final JTextField userNameTxt = new JTextField(6);

JButton loginButton = new JButton(“Change”);
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = “old is ” + oldStringTxt.getText();
data += “, new is: ” + new String(newStringTxt.getText() + “property is:” + propertyTxt.getText()
+ “username is:” + userNameTxt.getText());
statusLabel.setText(data);
OpenClose.oldString = oldStringTxt.getText();
OpenClose.newString = newStringTxt.getText();
OpenClose.propertyName = propertyTxt.getText();
OpenClose.userNameUnique = userNameTxt.getText();
SpecificFeildChange.b = true;
mainFrame.dispose();
}
});

controlPanel.add(oldStringlabel);
controlPanel.add(oldStringTxt);
controlPanel.add(newStringTxt);
controlPanel.add(newStringLabel);
controlPanel.add(loginButton);
controlPanel.add(propertyLabel);
controlPanel.add(propertyTxt);
controlPanel.add(usernameLabel);
controlPanel.add(userNameTxt);
mainFrame.setVisible(true);
}
}

 

ReadProperties.java:

package com.lmig.classes;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

public class ReadProperties {
static HashMap<String, String> hashMapAttributes;
static boolean loadBooleanvalue = false;
static Set<String> propertyValuesSet;
static void loadProperties() {
try {
File file = new File(“attributes.properties”);
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();

hashMapAttributes = new HashMap<>();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
hashMapAttributes.put(key, value);
loadBooleanvalue = true;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

 

atrributes.properties:

 

key1=username:
key2=password:
key3=address:
key4=hobbies:

 

input.txt:

username:madhu_sample1 password:Cena@1231 address:hyderabad1 hobbies:novels,Listening
username:madhu_sample2 password:Cena@1232 address:hyderabad2 hobbies:novels,Listening
username:madhu_sample3 password:Cena@1233 address:hyderabad3 hobbies:novels,Listening
username:madhu_sample4 password:Cena@1234 address:hyderabad4 hobbies:novels,Listening
username:madhu_sample5 password:Cena@1235 address:hyderabad5 hobbies:novels,Listening
username:madhu_sample6 password:Cena@1236 address:hyderabad6 hobbies:novels,Listening
username:madhu_sample7 password:Cena@1237 address:hyderabad7 hobbies:novels,Listening
username:madhu_sample7 password:Cena@1237 address:hyderabad7 hobbies:novels,Listening

 

Project Structure:

 

project.png

Feel free to contact me if you found any mistakes over post.Keep Posting…….Keep Sharing……Keep Smiling.. .