How to convert a text file content to String in JSP?
Hi,
I need to read the content of a text file and convert it into String and display it on to a JSP file.
But the codings below don't work. Please advise me on how can i display the text file content.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
File adCheck = new File("list.txt");
fis = new FileInputStream(adCheck);
int Length = adCheck.length();
byte arr[] = new byte[Length];
int dataRead = 0;
int totalData = 0;
while(totalData <Length)
dataRead = fis.read(arr,totalData,Length);
totalData += dataRead;
String Content = new String(arr);//byte array converted to String
arr = null;
InputStreamReader in=new InputStreamReader(fis);
StringWriter out=new StringWriter();
char[] buffer=new char[8192];
int sizeRead;
while ( ( sizeRead=in.read(buffer, 0, 8192) ) != -1 )
out.write(buffer, 0, sizeRead);
String content=out.toString();
Similar Messages
-
How to convert the TEXT file into an XML using plsql code
Hi all ,
I need to convert an TEXT file into an XML file how can i do it
Below is my sample TEXT file .
TDETL00000000020000000000000120131021115854ST2225SKU77598059 0023-000000010000
I want the above to be converted into the below format
<?xml version="1.0" encoding="UTF-8"?>
<txt2xml>
<!-- Processor splits text into lines -->
<processor type="RegexDelimited">
<regex>\n</regex>
<!--
This is used to specify that a message should be created per line in
the incoming file;
NOTE: this was designed to work with all the processors, however it
only works correctly with 'RegexDelimited' processors (check the
enclosing top processor type)
-->
<maxIterationsPerMsg>1</maxIterationsPerMsg>
<!-- For lines beginning with FHEAD (File Header) -->
<processor type="RegexMatch">
<element>FHEAD</element>
<regex>^FHEAD(.*)</regex>
<processor type="RegexMatch">
<element>OriginalLine</element>
<regex>(.*)</regex>
<consumeMatchedChars>false</consumeMatchedChars>
</processor>
<processor type="RegexMatch">
<element>LineSeq,Type,Date</element>
<regex>^(\d{10})(\w{4})(\d{14})$</regex>
</processor>
</processor>
<!-- For lines beginning with TDETL (Transaction Details) -->
<processor type="RegexMatch">
<element>TDETL</element>
<regex>^TDETL(.*)</regex>
<processor type="RegexMatch">
<element>OriginalLine</element>
<regex>(.*)</regex>
<consumeMatchedChars>false</consumeMatchedChars>
</processor>
<processor type="RegexMatch">
<element>LineSeq,TransControlNumber,TransDate,LocationType,Location,ItemType,Item,UPCSupplement,InventoryStatus,AdjustReason,AdjustSign,AdjustQty</element>
<regex>^(\d{10})(\d{14})(\d{14})(\w{2})(\d{4})(\w{3})([\w ]{13})([\w ]{5})(\d{2})(\d{2})([+-]{1})(\d{12})$</regex>
</processor>
</processor>
<!-- For lines beginning with FTAIL (File Tail) -->
<processor type="RegexMatch">
<element>FTAIL</element>
<regex>^FTAIL(.*)</regex>
<processor type="RegexMatch">
<element>OriginalLine</element>
<regex>(.*)</regex>
<consumeMatchedChars>false</consumeMatchedChars>
</processor>
<processor type="RegexMatch">
<element>LineSeq,TransCount</element>
<regex>^(\d{10})(\d{6})$</regex>
</processor>
</processor>
</processor>
</txt2xml>
ThanksSorry, that doesn't make much sense.
The XML you gave is a configuration file for txt2xml utility. It doesn't represent the output format.
Are you a user of this utility? -
How to convert CSV/Text files to XML format
Hi,
I am trying to convert a .csv/.txt(Flat) file(s) to XML format. How can i achive this?
Ex: I want to convert this text file to XML.
Book# first name last name ID# ID1# F#
B99 FRISBY NASIER LUCJ A A 3127 1
B131 HAWKINS MICHAEL LUCJ A A 3129 2
B313 KING JOSHUA CUCJ I I-DORM 10
B307 GRAVES KIMBERLY NUCJ F F-DORM 24-FL
R469 HEATH DARRELL SUCJ A A 3132 1
R212 PEREZ DARRELL SUCJ A A 3133 2
R62 COFFEY GREGORY NUCJ HC H C 3112 3FLOOR
R215 BLACKWELL DEREK LUCJ OOW W 01 1 Could anyone please suggest me if we have any open source java api to acheive this?
Thanks,
Srikanth.Have a look at [http://servingxml.sourceforge.net/|http://servingxml.sourceforge.net/] or [http://www.talend.com/|http://www.talend.com/]
-
How to convert a text file in lower case to upper case?
I've a beginner in java world and I just come through the tutorial in http://java.sun.com/docs/books/tutorial/essential/io/filestreams.html showing how to copy a text file:
import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
And I would like to ask how to covert all lower case letters in input file to upper case letter in output file at the same time of copying.
I guess it'll be using Character.toUpperCase(c), but I don't know how to do it actually.
Any help would be much appreciated.Hope this helps
import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
BufferedReader buff = new BufferedReader(in);
String c;
while ((c = buff.readLine()) != null)
out.write(c.toUpperCase());
in.close();
out.close();
} -
Converting a text file into a String
I need to convert a text file (in whatever format, in my case it would be xml and xsl files) in a String.
I made this methods:
public static String createStringFromFile(File f) {
StringBuffer buf = new StringBuffer();
try {
FileInputStream fInp = new FileInputStream(f);
byte[] byteArray = new byte[fInp.available()];
int bLetti = fInp.read(byteArray);
if (bLetti == fInp.available()) {
for (int i=0; i<fInp.available(); i++)
buf.append(Byte.toString(byteArray));
else
throw (new IOException("Errore nella lettura del file"));
fInp.close();
} catch (Exception e) {
ErrorManager.getError(e);
return (buf.toString());
public static String createStringFromFile(String fileName) {
StringBuffer buf = new StringBuffer();
try {
FileInputStream fInp = new FileInputStream(fileName);
byte[] byteArray = new byte[fInp.available()];
int bLetti = fInp.read(byteArray);
if (bLetti == fInp.available()) {
for (int i=0; i<fInp.available(); i++)
buf.append(Byte.toString(byteArray[i]));
else
throw (new IOException("Errore nella lettura del file"));
fInp.close();
} catch (Exception e) {
ErrorManager.getError(e);
return (buf.toString());
There are no compilation or runtime errors, but the result string is empty. Not null, empty. What should I do? :)Do you really want to use bytes and so on when java does it all for you?
Here's how I did it, hope it's useful.
public String getFileAsString(String fileName){
StringBuffer buffer = new StringBuffer();
try{
BufferedReader bRead = new BufferedReader(new FileReader(new File(fileName)));
String str = "";
while( (str = bRead.readLine()) != null ){
buffer.append(str);
}//end while
bRead.close();
}catch(Exception e){
System.err.println("in getFileAsString(): " + e.toString());
}//end try
return buffer.toString();
}//end getAsString() -
How to read a text file into a String?
and also write a text file from a String. I searched the forum and found this folowing code:
// Read and append... by Example
try{
String fileName = "text.txt"; // Filename
// Make the inputfile object
FileInputStream fi = new FileInputStream(fileName);
byte inData[] = new byte[fi.available()];
fi.read(inData); // Read
fi.close(); // Close
String text = new String(inData); // Make a textstring...
// Now, do whatever you want with the data... and append...
String textToAppend = "kjkjhjhKJ";
byte outData[] = textToAppend.getBytes();
// Make the outputfile (whith the 'append' boolean set to true
FileOutputStream fo = new FileOutputStream(fileName,true);
fo.write(outData);
fo.close();
}catch(Exception oops){}but it returns funny characters to the String from the text file and vice versa in writting the text file. Can anybody please help? Thank you.
kindoSee here for info on encodings:
http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html
Some common US encodings and common uses:
ASCII (DOS)
Cp1252 (Windows 9x)
UTF8 (XML)
import java.io.*;
public class TextFile extends File
private static String DEFAULT_ENCODING = "ASCII";
private File file;
private String encoding;
public TextFile(File file, String encoding)
super(file.getPath());
this.file = file;
this.encoding = encoding;
public TextFile(File file)
this(file, DEFAULT_ENCODING);
public String load() throws Exception
FileInputStream fis = new FileInputStream(file);
byte[] barr = new byte[fis.available()];
fis.read(barr);
fis.close();
return new String(barr, encoding);
public void save(String str) throws Exception
FileOutputStream fos = new FileOutputStream(file);
fos.write(str.getBytes(encoding));
fos.close();
} -
How to print a text file contents using java.
Using Input and Output streams I can add and retrive the contents to/from text file. But how to send this file contents to the printer or how to print the file.
Example from my code:
private void printErrorReport()
PrintJob pjob = getToolkit().getPrintJob(m_frame,null,null);
if (pjob != null) {
Graphics pg = pjob.getGraphics();
if (pg != null) {
String s = detailsArea.getText();
printLongString (pjob, pg, s);
pg.dispose();
pjob.end();
// Utility method needed
void printLongString (PrintJob pjob, Graphics pg, String s) {
int pageNum = 1;
int linesForThisPage = 0;
int linesForThisJob = 0;
// Note: String is immutable so won't change while printing.
if (!(pg instanceof PrintGraphics)) {
throw new IllegalArgumentException ("Graphics context not PrintGraphics");
StringReader sr = new StringReader (s);
LineNumberReader lnr = new LineNumberReader (sr);
String nextLine = " ";
int pageHeight = pjob.getPageDimension().height;
pageHeight -= 20;
Font helv = new Font("Arial", Font.PLAIN, 12);
//have to set the font to get any output
pg.setFont (helv);
FontMetrics fm = pg.getFontMetrics(helv);
int fontHeight = fm.getHeight();
int fontDescent = fm.getDescent();
int curHeight = 0;
try {
do {
nextLine = lnr.readLine();
if (nextLine != null) {
if ((curHeight + fontHeight) > pageHeight) {
// New Page
System.out.println ("" + linesForThisPage + " lines printed for page " + pageNum);
pageNum++;
linesForThisPage = 0;
pg.dispose();
pg = pjob.getGraphics();
if (pg != null) {
pg.setFont (helv);
curHeight = 0;
curHeight += fontHeight;
if (pg != null) {
pg.drawString (nextLine, 0, curHeight - fontDescent);
linesForThisPage++;
linesForThisJob++;
} else {
System.out.println ("pg null");
} while (nextLine != null);
} catch (EOFException eof) {
// Fine, ignore
} catch (Throwable t) { // Anything else
t.printStackTrace();
System.out.println ("" + linesForThisPage + " lines printed for page " + pageNum);
System.out.println ("pages printed: " + pageNum);
System.out.println ("total lines printed: " + linesForThisJob);
} -
How to read text file content in portal application?
Hi,
How do we read text file content in portal application?
Can anyone forward the code to do do?
Regards,
AnaghaCheck the code below. This help you to know how to read the text file content line by line. You can display as you require.
IUser user = WPUMFactory.getServiceUserFactory().getServiceUser("cmadmin_service");
IResourceContext resourceContext = new ResourceContext(user);
String filePath = "/documents/....";
RID rid = RID.getRID(filePath);
IResource resource = ResourceFactory.getInstance().getResource(rid,resourceContext);
InputStream inputStream = resource.getContent().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while(line!=null) {
line = reader.readLine();
//You can append in string buffer to get file content as string object//
Regards,
Yoga -
How to create a text file or XML file and add content through code into it...
Hi Everyone,
How to create a text file and add content through the code to the text file eform javascript ......orelse can we create a text file in life cycle designer...
Else say how to create a new XML file through the code and how some content like Example "Hello World".You can create a text file as a file attachment (data object) using the doc.createDataObject and doc.setDataObjectContents:
http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.450.html
http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.528.html
You can then export the file with the doc.exportDataObject method:
http://livedocs.adobe.com/acrobat_sdk/9.1/Acrobat9_1_HTMLHelp/JS_API_AcroJS.88.463.html
This won't work with Reader if it hasn't been given the file attachment usage right with LiveCycle Reader Extensions. -
How to convert a Excel file to a text file
Hi,
Anyone knows how to convert a excel file to a test file in java.
Thanks
Johnhi
The question is not easy to respond. The easy way is to use the excel program itself! You can read the contents of an excel file using jdbc. Have a look at javaworld for an introduction (�It�s Excel-lent�). Another approach is to use a native library like JExcelApi. Have a look at http://www.andykhan.com/jexcelapi/index.html
best regards
benny -
How to find SVG coordinates which have been converted to text file?
Hi all,
I am currently developing a system that will read svg file. As svg file can be converted to text file, i already converted it. The problem is how is i going to read the coordinates provided by svg?I just want to read all the coordinates, nothing else...I hope you all can help.
Regards..
Edited by: Tommy1986 on Jul 8, 2008 12:45 AM
Edited by: Tommy1986 on Jul 8, 2008 12:47 AM<?xml version="1.0" standalone="no"?>
<svg width="6.666667in" height="4.166667in" viewBox="-0.000000 -0.000000 6.666667 4.166667">
<g transform="matrix(1,0,0,-1,0,4.166667)">
<polyline id="1" stroke="#000000" stroke-width="0.007874" fill="none" points="1.218750,2.614583 1.239583,2.666667 1.364583,2.791667 1.395833,2.885417 " />
<polyline id="2" stroke="#000000" stroke-width="0.007874" fill="none" points="1.656250,2.802083 1.364583,2.802083 1.322917,2.541667 1.296875,2.489583 1.296875,2.364583 1.406250,2.260417 1.468750,2.244792 1.875000,2.244792 " />
<path id="3" d=" M1.887762,2.247006 A0.531129,0.531129 0 0,1 1.657914,2.815088 " fill="none" stroke="#000000" stroke-width="0.007874" />
</g>
</svg>
Hi BatraAnkit,
Thank you very much for replying in my post. I really appreciate it Above is an example of svg file. What I am tring to do is to read only the polyline and the path collumn. Is there anyway to do it? As you can see, the svg is in xml format. Looking forwards to your reply..
Regards,
Tommy1986 -
Does anyone know how to convert an XML file to a readable file?
All,
I have been using an APP called "SMS Backup & Restore" to backup my message conversations to my Laptop PC. It works fine BUT the backup file, once in my PC, has an XML extent such as "filename.XML"
I would like to read and/or print and/or save the text message file so does anyone know how to convert the XML file to something else so it shows all the messages without all the formatting instructions.
When I try to see the XML file it shows all the formatting. If I replace the .XML with .TXT that too shows all the formatting mixed in with the text message narrative.
When I look at the XML file in SMS Backup & Restore in the Charge phone it looks great showing all the messages just as they were on the phones display. The problem with this is that there is no way to print or read or save the messages as they appear in the file from the phone itself. I tried screen capture but if you have, let's say, a 28 message conversation you have to do 7 or 8 screen captures to get them all.
If only I could convert the XML in my PC to something that is printable or savable or readable that would be the "cats meow."
Anyone know how???
JerryF
PS, You might take a look at my related post.
https://community.verizonwireless.com/message/809832#809832Ann154,
You were correct again. I deleted everything I had done to date and re-did the entire SMS backup of my 28 message conversation again and YES I was able to open it using IE-8. It looks great and it prints great and life is good! I am going to go make a donation.
Thanks again for the help. I marked this thread as answered by you.
JerryF -
How to attach a text file as an attachment to email message?
Hello Everybody,
I have a .csv file, in which details about emp-id, emp-name, e-expenses for Reimbursement and email address are stored.
My application reads this .csv file, and sends a mail to each employee with his id, salary details in text format. (by changing content type to "text/plain") The code is working fine. But,
My problem is:
The message is sent as message body to the end user.
The end user / the person who receives this mail will not be a technical person. So,
1) If he trys to take a print out of this e-mail, He get only half of it.(as no. of colums will be more than paper size).
2) I am finding alignment problem. IF employee name is too big, other columns will shift to right and data will not be exactly under column header. (it is going in zig zag way)
So, I thought sending text file with all the details as an attachment might do well.
But, I don't know how to attach a text file to email-message body.
code
try
{ String s1="";
File f1 = new File(the path);
FileInputStream fstream = new FileInputStream(f1); //new
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
int count=0;
while((s1=br.readLine())!=null )
count++;
//out.println("within while loop "+count);
StringTokenizer st = new StringTokenizer(s1,",");
if ((st.hasMoreTokens())&&(count>1))
String a=st.nextToken().trim();
String b=st.nextToken();
String c=st.nextToken();
String d=st.nextToken();
String e=st.nextToken();
String f=st.nextToken();
String g=st.nextToken();
String h=st.nextToken();
String i=st.nextToken();
String j=st.nextToken();
String k=st.nextToken();
String l=st.nextToken();
String m=st.nextToken();
String n=st.nextToken();
String o=st.nextToken();
String p=st.nextToken();
String q=st.nextToken();
String mail=st.nextToken();
String s=st.nextToken();
//out.println("b="+b+"c="+c+"d="+d+"e="+e+"f="+f+"mail="+mail);
%>
<%
String to =mail;
String from =request.getParameter("fromadd");
String subject ="Statement of Expenses";
String smtp ="mail.xxxxxxxxxx.com";
String message="";
message=message.concat("EMP ID");
message=message.concat(" ");
message=message.concat("Name");
message=message.concat(" ");
message=message.concat("Dept No.");
message=message.concat(" ");
message=message.concat("Acc No.");
message=message.concat(" ");
message=message.concat("*****************************************************************************************");
message=message.concat(a);
message=message.concat(" ");
message=message.concat(b);
message=message.concat(" ");
message=message.concat(c);
message=message.concat(" ");
message=message.concat(d);
Properties props = System.getProperties();
// Puts the SMTP server name to properties object
props.put("mail.smtp.host", smtp);
// Get the default Session using Properties Object
Session session1 = Session.getDefaultInstance(props, null);
// Create a New message
MimeMessage msg = new MimeMessage(session1);
// Set the From address
msg.setFrom(new InternetAddress(from));
// Setting the "To recipients" addresses
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to, false));
/* // Setting the "cc recipients" addresses
msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(cc, false));
// Setting the "Bcc recipients" addresses
msg.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(bcc, false)); */
// Sets the Subject
msg.setSubject(subject);
// set the meaasge in HTML format
msg.setContent(message,"text/plain");
// Set the Date: header
msg.setSentDate(new java.util.Date());
// Send the message
Transport.send(msg);
// Display Success message
result =result.concat("<tr><td>"+b+"</td>"+"<td>"+to+"</td></tr>");
}//end of if of hasmore element
}// end of while loop
out.println(result);
}catch(Exception e)
// If here, then error in sending Mail. Display Error message.
result="Unable to send your message";
out.println("e="+e);
Any help will be appreciated.
Thanks and regards.
Ashvini<html>
<p>
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText("Your Messages");
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource("Your Attachments");
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);
msg.saveChanges();
msg.writeTo(System.out);
msg.setSubject(subject);
Transport.send(msg);
</p>
<B><U>See you can add above code in your program and see the magic</U></B>
Bye
regards--
Ashish
</html> -
How to read a text file using Java
Guys,
Good day!
Please help me how to read a text file using Java and create/convert that text file into XML.
Thanks and God Bless.
Regards,
I-Talkpublic void fileRead(){
File aFile =new File("myFile.txt");
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
while (( line = input.readLine()) != null){
catch (FileNotFoundException ex) {
ex.printStackTrace();
catch (IOException ex){
ex.printStackTrace();
}This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
cheers
Mohammed Jubaer Arif. -
Need to read text file content and have to display it in multiline text box
dear all,
Need to read text file content and have to display it in multiline text box.
actually im new to file handling. i have tried up to get_line and put_line.
in_file := TEXT_IO.FOPEN ('D:\SAMPLE.txt', 'r');
TEXT_IO.GET_LINE (in_file,linebuf);
i dont know how to assign this get_line function to text item
pls help me in this regards,Simply write:
in_file := TEXT_IO.FOPEN ('D:\SAMPLE.txt', 'r');
TEXT_IO.GET_LINE (in_file,linebuf);
:block2.t1 := chr(10)||:block2.t1||chr(10)||linebuf;
chr(10) --> is for new line character
Maybe you are looking for
-
Is it possible to make a DVD rom work on Sparc Ultra 5 running Solaris 2.6?
I have been asked to try and get a DVD drive to work on a sparc ultra 5 running Solaris 2.6. Its been a while since I have done much with an ultra 5. My first reaction was no. However I thought that I should ask just in case it can be done. Its got t
-
Error: Logical end-of-file reached during read operation. Result Code = -39
Hello all, Recently, I have been suddenly getting this error message: "Logical end-of-file reached during read operation. Result Code = -39." In my case, when it does come up, it always pops up during the recording of an audio take. Almost immediatel
-
Improve autosubmit performance in ADF JSF in Jdev 11g R1.
we are using autosubmit for taking item value w,th button, cascade list etc. (at inputtext item, list item). But low bandwith our user feel a slowness when navigate out of items. mouse cursor is turn to waiting even for inputtext. is there any way to
-
Hello SDN I'm new to portal and facing problem with button event management .when i triggered event its giving error that eventhandler could not be found .Where should i write my event handler in"doProcessAfterInput()" or elsewhere waiting for help
-
My computer updated iTunes to 7.4.2 and now it takes over 2 minutes (yes, seriously) for the program to open once I click the icon. Any one else have this problem or know of a fix?