Reading file line by line in jsp - java

I have a text file containing various information such as name, age, address and ID.
Tommy
14
Gold coast
11994452
I would like to be able to pass the data into a jsp webpage and edit it using a web form.
I have a working file reading in jsp format that is able to read the file and display the information on the webpage, however i am confuse as to how does the web form edit various information such as name in the text file.
**Example: Tommy has a new address and i would like to use a web form to change the value in the text file
<%
String fileName = "/test/putty.txt";
InputStream ins = application.getResourceAsStream(fileName);
try
{
if(ins == null)
{
response.setStatus(response.SC_NOT_FOUND);
}
else
{
BufferedReader br = new BufferedReader((new InputStreamReader(ins)));
String data;
while((data= br.readLine())!= null)
{
out.println(data+"<br>");
}
}
}
catch(IOException e)
{
out.println(e.getMessage());
}
%>
Should i define the file by lines ? Eg line 1 = name , line 2 = age, line 3 = address and write back to the specific line ? If so how can this be done ?
Thanks in advance

Related

How to read a text file which contain multiple json data and which divide by the unice separator. in android kotlin

*** My the target work is the read the text file line by line using readline() function and then when came to the separator then send 1st JSON to the JSON parser...
1st I will share text file screen short : - enter image description here
This screen short, you will see the red mark which is the used separator.
but my problem is that when I read the text file from the assets folder and read it line by line using a stream reader and separate the separator they can not get the proper data.
I will share the code what I will do
private fun loadJSONFromAsset(){
//function to load the JSON from the Asset and return the object
var data: String? = null
try {
val jsonFileLoad = assets.open("json.txt")
val inputStreamReader = InputStreamReader(jsonFileLoad)
val bufferedReader = BufferedReader(inputStreamReader)
val stringBuilder = StringBuilder()
var str : String
while ( bufferedReader.readLine().also { str = it } != null){
if (str != "|"){
stringBuilder.append(str)
} else {
data = stringBuilder.toString()
stringBuilder.delete(0, stringBuilder.length)
}
Log.e(TAG, ""+data)
}
jsonFileLoad.close()
} catch (ex : IOException){
ex.printStackTrace()
}
return data
}
this the new code and it return in log it null
this is my file read function which read the file but can not separate
i also send the error image enter image description here

how to create a file with a specific name and specific text

I have a file that contain tweets and its ID for example
1 what a nice day //1 is the ID and "what a nice day" is the tweet text
2 how are you doing //2 is the ID and "how are you doing" is the tweet text
.
.
. etc
I want to create a new file for each line and name it with the ID and inside this file I want to put the tweet text
take the first line as an example "1 what a nice day"
the file name should be(1.txt)and inside that file "what a nice day"
I really dont have any idea how to do this can you please help me?
The will help you I hope :
public static void readSplitWrite(String pathToFile){
//To recognize how are your sentences : between 1 and 25 digit, then some spaces, and then what you want
Pattern patt = Pattern.compile("([0-9]{1,25})\\s*(.*)");
try {
//Read over all the lines of your file
for(String line : Files.readAllLines(Paths.get(pathToFile),Charset.forName("UTF-8"))){
//Catch the different parts of the string (group(0) is the hole sentence, group(1) is inside first (), group(2) is inside second ()
Matcher m = patt.matcher(line);
if(m.find()){
//Open a file, in UTF-8 encoding (to be able to read Arabic character, as name the ID
Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(m.group(1)+".txt"), "UTF-8"));
try {
//write the content into
out.write(m.group(2));
}catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//Just the name if the file is in the folder, if not write absolute path
String pathToFile = "Text.txt";
readSplitWrite(pathToFile);
}
This code will read your file, and then create a new File for each line, with as name the number, and as content the sentence
If there is any problem, tell me in comment
Edit : I commented better the code to help you

Get id number and if found, Delete it [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java - Find a line in a file and remove
I have a code that Get id number and search for its records, if exist, display it.
I want if found, delete it record.
One solution for delete a line( a user record) is create another file and copy all lines without found record.
can anyone tell me another solution? (Simple solution)
my BookRecords.txt file is this:
Name Date Number
one 2002 22
two 2003 33
three 2004 44
four 2005 55
my Code to find :
String bookid=jTextField2.getText();
File f=new File("C:\\BookRecords.txt");
try{
FileReader Bfr=new FileReader(f);
BufferedReader Bbr=new BufferedReader(Bfr);
String bs;
while( (bs=Bbr.readLine()) != null ){
String[] Ust=bs.split(" ");
String Bname=Ust[0];
String Bdate=Ust[1];
String id = Ust[2];
if (id.equals(bookid.trim())
jLabel1.setText("Book Found, "+ Bname + " " + Bdate);
break;
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
please help to delete a Line(a Record)
Thanks.
Working on a single text file is - uhm - a bit strange. But I would recommend, that you create a new text file (output):
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
Only write the lines that don't match the book's ID.
while (...) {
...
if (!id.equals(bookid.trim())) {
out.println(bs);
}
}
out.close();
Later you can rename the file, if you like.
replace the entire line in the text file with a backspace character when found
\b

read data from a file in java

I have a text file in the following format:
Details.txt
The file is a .txt file. I want to read course title from this file and print corresponding textbook and instructor information. But i am not sure about what process to follow ? storing the information in an array won't be efficient! How should i proceed ? NOTE: I can't change the info in the file, it should not be changed!! obviously the file will be read by the following code:
File newFile=new File("C:/details");
but how should i extract the data from this file according to the labels course title, textbook and instructor!?
First read the file correctly line by line, and search for your entered course title, lets consider "Java"
Now you hit your title and you know you need 3 consecutive lines from your file as all information related to that title are there.
if(str.startsWith(title)); { // for title = "Java"
line1 = 1st line // contains ISBN and First Name
line2 = 2nd line // Title and Last Name
line3 = 3rd line // Author and Department
line4 = 4th line // Email
break; // this will take you out of while loop
}
Now on those four lines do string operations and extract your data as you need and use it.
I am home so I can't give you exact code. But if you follow this it will solve your issue. Let me know if any problem you got while doing this.
Follow this to get some info on String operations
Use String Tokenizer and separate each string and then store them in a Linked List or Array List. Have Separate List for each title like course title, instructor etc. and then print them
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
you can use FileUtils.readFileToString(new File(""C:/details.txt");
Now you can extract the required data based on your wish
Use Scanner class
Scanner s=new Scanner(new File("C:/Details.txt"));
while(s.hasNext())
{
System.out.println(s.nextLine());
}
if you want in work by word then use String Tokenizer
see this article

Read email contents using Apache Commons Email

I've different properties file as shown below:
abc_en.properties
abc_ch.properties
abc_de.properties
All of these contain HTML tags & some static contents along with some image urls.
I want to send email message using apache commons email & I'm able to compose the name of the template through Java using locale as well.
String name = abc_ch.properties;
Now, how do I read it to send it as a Html Msg parameter using Java?
HtmlEmail e = new HtmlEmail();
e.setHostName("my.mail.com");
...
e.setHtmlMsg(msg);
How do I get the msg param to get the contents from the file? Any efficient & nice solun?
Can any one provide sample java code?
Note: The properties file has dynamic entries for username & some other fields like Dear ,....How do I substitute those dynamically?
Thanks
I would assume that *.properties is a text file.
If so, then do a File read into a String
eg:
String name = getContents(new java.io.File("/path/file.properties");
public static String getContents(File aFile) {
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
InputStreamReader fr=new InputStreamReader(new FileInputStream(aFile), "UTF8");
input = new BufferedReader( fr );
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
//ex.printStackTrace();
}
catch (IOException ex){
//ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
//ex.printStackTrace();
}
}
return contents.toString();
}
regards
Hi Mike,
Well, I kind of guess that you are trying to send mails in multiple languages by rendering the elements from different property files at runtime. Also, you said "locale". Are you using the concept of "Resource Bundles )"? Well, in that case before you send mails,
1)You need to understand the naming conventions for naming a property file, without which the java compiler will not be able to load the appropriate property file at run time.
For this read the first page on the Resource Bundles page.
2) Once your naming conventions is fine, you can load the appropriate prop file like this:
Locale yourLocale = new Locale("en", "US");
ResourceBundle rb = ResourceBundle.getBundle("resourceBundleFileName", yourLocale);
3) Resource Bundle property file is nothing but a (Key,Value) pairs. Hence you can retrieve the value of a key like this:
String dearString = rb.getString("Dear");
String emailBody= rb.getString("emailBody");
4) You can later use this values for setting the attributes in your commons-email api.
Hope you find this useful!

Categories