I have a csv file that basically mimics a database and my goal is to remove a row from that csv if the csv file contains that username input I provide
the current csv file is:
Jack chan,customer,jack#yorku.ca,jack12,3144134414,13 Arboretum,user2
Donald tusk,customer,donald#yorku.ca,donald1,1213141114,14 Arboretum,user3
tom jack,customer,tom11#yahoo.com,tom44,131344122,14 wells st,user34
jack,parking officer,12rfw#hmail.com,jack,12131131134,12ddcscs,peo1
jewel khan,parking officer,jkhan#hotmail.com,jwel12,2131412141,12 wliis str,peo2
shane li,parking officer,shane#gmail.com,shaneli,1343513414,13 mac st,peo33
james chang,parking officer,james15#gmail.com,james12,31452434114,13 chang st,peo77
my objective is to remove the row of say Shane li using his username "shaneli" and not causing any change to other data. but the current code I have is not causing the file's other data to change
the expected output csv file is row with shaneli gets deleted with other rows remaining intact:
Jack chan,customer,jack#yorku.ca,jack12,3144134414,13 Arboretum,user2
Donald tusk,customer,donald#yorku.ca,donald1,1213141114,14 Arboretum,user3
tom jack,customer,tom11#yahoo.com,tom44,131344122,14 wells st,user34
jack,parking officer,12rfw#hmail.com,jack,12131131134,12ddcscs,peo1
jewel khan,parking officer,jkhan#hotmail.com,jwel12,2131412141,12 wliis str,peo2
james chang,parking officer,james15#gmail.com,james12,31452434114,13 chang st,peo77
this is the code java code I have and I need a java solution:
private static String userPath = "/CSVs/database.csv";
public void removeUser(String name,String userType,String email,String userName,String phoneNumber,String address,String password) {
// FIX THIS
String tmpFile = "tmp.csv";
// String target1 = ""; String target2 = ""; String target3 = ""; String target4 = ""; String target5 = "";String target6 = "";String target7 = "";
String target = "";
File oldFile = new File(userPath);
File newFile = new File(tmpFile);
System.out.println(userName);
try {
FileWriter fw = new FileWriter(tmpFile, true);
BufferedWriter bfw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bfw);
x = new Scanner(new File(userPath));
x.useDelimiter("[,\n]");
while (x.hasNext()) {
target = x.next();
if (!target.equals(userName)) {
pw.printf("%s,%s,%s,%s,%s,%s,%s\n", name, userType,email,userName,phoneNumber,address,password);
// pw.println(target + "," + target + "," + target + "," + target + "," + target + "," + target + "," + target);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dmp = new File(userPath);
newFile.renameTo(dmp);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Please advice
Thanks in advance !!
Solution
The way I've come up with is to do the following:
Create a new file
If the username is not equal, add line, otherwise skip it
Just as we've listed out our steps, we can create a function to do each one.
Code
1) Creating a new file
private void createFile(){
try {
File myObj = new File("CSVs/tmpFile.csv");
} catch (IOException e) {
e.printStackTrace();
}
}
We can then create the file which will be stored at the desired file path and stored as tmpFile.csv.
2) If the username are not equal, add line
private void addDataContents(String userNameToDelete){
try{
String userPath = "CSVs/database.csv";
BufferedReader csvReader = new BufferedReader(new FileReader("CSVs/database.csv"));
String row;
FileWriter myWriter = new FileWriter("CSVs/tmpFile.csv");
while (((row = csvReader.readLine()) != null)){
String[] line = row.split(",");
if (!line[3].equals(userNameToDelete)){
myWriter.write(row + "\n");
}
}
myWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
We then read through the contents of database.csv. We read every line one by one and split the line up by commas as it is a CSV file ( Comma Separated Values ). As the username will always be stored in the 3rd index, we can compare the username we wish to delete with the value stored at the index. If they are not the same, we can go ahead and write the line to our new file. If they are the same, our loop will just continue onto the next line.
Final Notes
I hope everything is easy to read and understandable.
You need to delete the whole row containing specific data from a CSV file. The Java code will be rather long if you try to use the high-level language to do this. It is very simple to accomplish the task in SPL, an open-source Java package. You just need one line of code, as shown below:
A
1
>file("tmp.csv").export#c(file("database.csv").import#wc().select(~(4)!=userNameToDelete))
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as removeUser.splx and invoke it in Java in the same way you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call removeUser(?)");
st.setObject(1,"shaneli");
st.execute();
…
As a way to learn java, I attempted to write something simulating a bank(adding or removing numbers). I succeeded in creating a file(if one does not exist already), and then read from it, but when I attempt to write to it, it fails. I started with FileWriter, where it just erased the text in the document(balance.txt). I then tried BufferedWriter, and it wrote to the document, but it was just symbols instead of actual text/numbers. I'm aware that I'm a newbie when it comes to coding, but is there a solution to this? Thank you.
if (choice.equals("ADD")){
System.out.println("Currently selected: " + choice);
//write to file
try {
String filePath = "C:\\Users\\user\\Desktop\\programming\\projects\\java\\RandomStuff\\Bank\\balance.txt";
// System.out.println("How much would you like to add?");
// Scanner inputAdd = new Scanner(System.in);
// String balanceToAdd = inputAdd.nextLine();
// writeToFile.write(balanceToAdd);
int balanceToAdd = 1;
BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
out.write(balanceToAdd);
out.close();
System.out.println("Added: " + balanceToAdd);
} //try end
catch(IOException e){
System.out.println("Error(line56): " + e.getMessage());
}
public FileWriter(String fileName,
boolean append)
I think you should use append to edit your file.
BufferedWriter out = new BufferedWriter(new FileWriter(filePath,true));
Writing a program in java I'm trying to read the content of a file which is treated as a storage. I have a function to modify the amount of an object in the store, which is organized with one line per product, where the first word is the prodCode, and the second is the amount of it.
This is the function:
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
FileWriter toFile = new FileWriter(magazzino);
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
toFile.write(newContent);
toFile.close();
fromFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
And the result of it is that it won't enter the while cycle because the first readLine result null, though the file is correctly formatted, the 'amountRequest' function works properly and the input is correct.
Magazzino.txt:
1 12
3 25
4 12
You're probably having trouble because you're trying to read and write the file at the same time, with different file handles. I'd suggest reading the file first, then closing the FileReader, then creating a FileWriter to write to it.
The issue is that before you have read the contents of the file, you are creating an instance of FileWriter which will clear the file.
FileWriter toFile = new FileWriter("Magazzino.txt"); will clear the file
The solution is to just create the instance of FileWriter after you are done reading the file.
public static void modifyAmount(String prodCode, String newAmount){
try{
File magazzino = new File("Magazzino.txt");
BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
String oldContent="";
String line;
String lineToReplace = prodCode + " " + amountRequest(prodCode);
String newLine = prodCode + " " + newAmount;
while((line = fromFile.readLine()) != null){
oldContent = oldContent + line + "\n";
System.out.println("leggendo " + line);
}
fromFile.close();
System.out.println(oldContent);
String newContent = oldContent.replaceAll(lineToReplace, newLine);
FileWriter toFile = new FileWriter(magazzino);
toFile.write(newContent);
toFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
You open a file twice, simultaneously for reading and writing.
As soon as you do this line,
FileWriter toFile = new FileWriter(magazzino);
your file is erased. Check it yourself.
Actually, with this line you are creating a new empty file for writing instead of the old one.
I'd suggest read file, then close, then write.
You can also try to pen file for append : new FileWriter("filename.txt", true);
This will not erase old file, allowing you to read it. But the new data will be appended to the end, though.
If you want to use you file as a state or storage, I'd suggest to look at sqlite: https://www.sqlite.org/index.html
This is my code, I am trying to write a text file replacing "Up" and "Right" with ↑ and →. The problem is that the text file output is: "→ ↑"(this is not what i wanted) and the console output is "↑ →".
private static void print(String t){
File log = new File("a.txt");
String raw = t;
raw = raw.replaceAll("Up", " \u2191 "); //↑
raw = raw.replaceAll("Right", " \u2192 "); //→
try{
FileWriter fileWriter = new FileWriter(log, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(raw + "\n");
System.out.println(raw + "\n")
bufferedWriter.close();
}catch(IOException e) {}
}
I think it may be an encoding error, but I dont know how to fix it.
First of all, it's best to specify the encoding (you probably want UTF-8) before you write your file.
private static void print(String t){
File log = new File("a.txt");
String raw = t;
raw = raw.replaceAll("Up", " \u2191 ");
raw = raw.replaceAll("Right", " \u2192 ");
try{
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(log), "UTF-8"));
bufferedWriter.write(raw + "\n");
System.out.println(raw + "\n");
bufferedWriter.close();
}catch(IOException e) {}
}
Then, you need to make sure that your file viewer is also set to UTF-8. It seems that your file viewer might be viewing the file in ANSI instead. Changing that setting would depend on your file viewer -- try Googling "[your file viewer name] UTF-8".
I am new to Java and trying to save a multi line string to a text file.
Right now, it does work within my application. Like, if I save the file from my application and then open it from my application, it does put a space between lines. However, if I save the file from my app and then open it in Notepad, it is all on one line.
Is there a way to make it show multi line on all programs? Here's my current code:
public static void saveFile(String contents) {
// Get where the person wants to save the file
JFileChooser fc = new JFileChooser();
int rval = fc.showSaveDialog(fc);
if(rval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
//File out_file = new File(file);
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(contents);
out.flush();
out.close();
} catch(IOException e) {
messageUtilities.errorMessage("There was an error saving your file. IOException was thrown.", "File Error");
}
}
else {
// Do nothing
System.out.println("The user choose not to save anything");
}
}
depending on how you are constructing your string, you may just be running into a line ending problem. Notepad does not support unix line endings (\n only) it only supports windows line endings (\n\r). try opening your saved file using a more robust editor, and/or make sure you are using the proper line endings for your platform. java's system property (System.getProperty("line.separator")) will get you the proper line ending for the platform that the code is running on.
while you're building your string to be saved to the file, rather than explicitly specifying "\n" or "\n\r" (or on the mac "\r") for your line endings, you would instead append the value of that system property.
like so:
String eol = System.getProperty("line.separator");
... somewhere else in your code ...
String texttosave = "Here is a line of text." + eol;
... more code.. optionally adding lines of text .....
// call your save file method
saveFile(texttosave);
Yea as the previous answer mentions the System.getProperty("line.seperator").
your code doesn't show how you created String contents but since you said you were new to java I thought i'd mention that in java concatenating Strings is not nice since it creates a. If you are building the String by doing this:
String contents = ""
contents = contents + "sometext" + "some more text\n"
Then consider using java.lang.StrinBuilder instead
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("sometext").append("somre more text\n");
...
String contents = strBuilder.toString();
Another alternative is to stream what ever your planning to write to a file rather than building a large string and then outputting that.
You could add something like:
contents = contents.replaceAll("\\n","\\n\\r");
if notepad does not display correctly. However you might run into a different problem: at each save/load you will get multiple \r chars. Then to avoid that at load you would have to call the same code above but with reversed parameters. This is really an ugly solution just to get the text to display properly in notepad.
I had this same problem my guy friend, after much thought and research I even found a solution.
You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file.
if something does not make sense, I'm sorry is google translator and I who do not speak English.
Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();
Text.add(TextArea.getText());
SaveFile(NameFile, Text);
}
public void SaveFile(String name, ArrayList< String> message) {
path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";
File file1 = new File(path);
try {
if (!file1.exists()) {
file1.createNewFile();
}
File[] files = file1.listFiles();
FileWriter fw = new FileWriter(file1, true);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < message.size(); i++) {
bw.write(message.get(i));
bw.newLine();
}
bw.close();
fw.close();
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
fw = new FileWriter(file1, true);
bw = new BufferedWriter(fw);
while (br.ready()) {
String line = br.readLine();
System.out.println(line);
bw.write(line);
bw.newLine();
}
br.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error in" + ex);
}