Link to home
Start Free TrialLog in
Avatar of gchen91789
gchen91789

asked on

How to read, insert, update and write a comma seperated text files?

I need some help on the following:

How to read, update and write a comma seperated text file into textarea?

How to sort the text file after insert a new record (if the first five char is the key) and redisplay through JSP?


Thanks.
Avatar of rrz
rrz
Flag of United States of America image

Try this. First manually create the file in your web app's root folder.
<%@ page import="java.util.*,java.io.*"%>
<%
  File file = new File(application.getRealPath("/text.txt"));
  String text = request.getParameter("text");
  if(text == null){
                   char[] data = new char[(int)file.length()];
                   FileReader fr = new FileReader(file);
                   int charsRead = fr.read(data);
                   text = new String(data, 0 , charsRead);
                   fr.close();
  }else{
        String[] words = text.split(",");
        Arrays.sort(words);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i<words.length;i++){
             sb.append(words[i] + ",");
        }
        text = sb.toString();
        FileWriter fw = new FileWriter(file);
        fw.write(text);
        fw.close();
       }
%>
<html>
 <body>
       <form method="post">
                   <textarea name='text'><%=text%></textarea>
                   <input Type='submit' value='Submit'/>
       </form>
 </body>
</html>
Avatar of gchen91789
gchen91789

ASKER

Thanks for your help. But more question for you,

File file = new File(application.getRealPath("/text.txt"));

I try to change "/text.txt" to  "C:" + File.separator + "folder1" + File.separator + "folder2" + File.separator + "text.txt";
I got the application path + file path, How do I point the text.txt to "C:\folder1\folder2\text.txt?

Thanks.
Did you try ?
File file = new File("C:\\folder1\\folder2\\text.txt"));
or
File file = new File("C:/folder1/folder2/text.txt"));
O.K. after I try it, all the data show on the textarea, but it did not separate by line. In addition, how to separate each field with space or tab instead the comma.

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of rrz
rrz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> How to sort the text file after insert a new record (if the first five char is the key)

You can load the contents into an ArrayList and then use Collections.sort () - define your own comparator