File Bytes to String

I'm trying to decode a file, when i use this codepublic void returnFile(String filename) throws FileNotFoundException, IOException {
//       A FileInputStream is for bytes
       FileInputStream fis = null;
       try {
            fis = new FileInputStream(filename);
            byte[] buf = new byte[4 * 1024];  // 4K buffer
            int bytesRead;
            while ((bytesRead = fis.read(buf)) != -1) {
                 out.write(buf, 0, bytesRead);
       finally {
            if (fis != null) fis.close();
  }with the result beeing printed directly,
but in an other case i don't have access to the out variable, so i want to return a string from a function, so i have thispublic static String returnFile2(String filename)
     throws FileNotFoundException, IOException {
//          A FileInputStream is for bytes
          FileInputStream fis = null;
          StringBuffer buffer = new StringBuffer();
          try {
               fis = new FileInputStream("C:/eclipse/workspace/rbtTranform/WebContent/images/15x15/V.gif");
               byte[] buf = new byte[4 * 1024];  // 4K buffer
               int bytesRead;
               while ((bytesRead = fis.read(buf)) != -1) {
                    buffer.append(new String(buf).trim());
          finally {
               if (fis != null) fis.close();
          return buffer.toString();
     }The problem is that in this second funcion, i return the file contents as a String, they are not like in the first function, and i can't "re-encode" the data back to original file (as i can with the first function)
Can anyone help me?

I want to make a MultiPart Response, i am using this in a XSLT file that call a function that is supposed to take a file and return its contents as a String (the second method i posted)
I can't use the first one, because from the XSLT i can't send the out parameter, so that i could write on it
That's also why i can't handle and image as an image
It's a bit confusing i know
But if you could gimme a hint...

Similar Messages

  • 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.
    kindo

    See 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();
    }

  • Encoded double byte characters string conversion

    I have double byte encoded strings stored in a properties file. A sample of such string below (I think it is japanese):
    \u30fc\u30af\u306e\u30a2
    I am supposed to read it from file, convert it to actual string and use them on UI. I am not able to figure how to do the conversion -- the string contains text as is, char backslash, char u, and so on. How to convert it to correct text (either using ai::UnicodeString or otherwise)?
    Thanks.

    Where did this file come from? Some kind of Java or Ruby export? I don't think AI has anything in its SDK that would natively read that. You could just parse the string, looking for \u[4 characters]. I believe if you created a QChar and initialized it with the integer value of the four-character hex string, it would properly create the character.

  • How to convert byte into string

    can any tell me how to convert byte into string
    when im an debugging thid code in eclipse it shows the result in integer format instead of string but in command prompt it is showing result in string format..........plz help
    package str;
    import java.io.*;
    public class Testfile {
    public static void main(String rags[])
    byte b[]=new byte[100];
    try{
    FileInputStream file=new FileInputStream("abc.txt");
    file.read(b,0,50);
    catch(Exception e)
         System.out.println("Exception is:"+e);
    System.out.println(b);
    String str=new String(b);
    System.out.println(str);
    }

    Namrata.Kakkar wrote:
    errors: count cannot be resolved and Unhandled exception type Unsupported Encoding Exception.
    If i write an integer value instead of "count" then Unhandled exception type Unsupported Encoding Exception error is left.This is elementary. You need to go back to [http://java.sun.com/docs/books/tutorial/|http://java.sun.com/docs/books/tutorial/] .

  • How to covert byte[] to String format

    I'm trying to print the reultset into a text file, but I'm having a prb converting byte[] to String.
    Here is my Code
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("C:\\MyFile.txt")));
    while (rs1.next()) {
    byte[] _id         = rs1.getBytes(1);
    String _FName   = rs1.getString(2);
    String _LName   = rs1.getString(3);
    out.print(_id);
    String s = String.valueOf(_id);
    out.println("-Sales_Acct--:"+s+"--Name--"+FName+"-Numb-"+LName);
    I'm supposed to get 0000690D ( byte[] value )but in the text file it is printing as [B@1add
    I donno what's wrong with my code!!
    your help is greatly appreciated!

    http://forum.java.sun.com/thread.jsp?forum=48&thread=143531
    do you two know one another?

  • Reading & writing to file using ArrayList String incorrectly (2)

    I have been able to store two strings (M44110|T33010, M92603|T10350) using ArrayList<String>, which represent the result of some patient tests. Nevertheless, the order of these results have been stored correctly.
    E.g. currently stored in file Snomed-Codes as -
    [M44110|T33010, M92603|T10350][M44110|T33010, M92603|T10350]
    Should be stored and printed out as -
    M44110|T33010
    M92603|T10350
    Below is the detail of the source code of this program:
    import java.io.*;
    import java.io.IOException;
    import java.lang.String;
    import java.util.regex.*;
    import java.util.ArrayList;
    public class FindSnomedCode {
        static ArrayList<String> allRecords = new ArrayList<String>();
        static public ArrayList<String> getContents(File existingFile) {
            StringBuffer contents = new StringBuffer();
            BufferedReader input = null;
            int line_number = 0;
            int number_of_records = 0;
            String snomedCodes = null;
            ArrayList<String> complete_records = new ArrayList<String>();
            try {
                input = new BufferedReader( new FileReader(existingFile) );
                String current_line = null;
                while (( current_line = input.readLine()) != null) {
                    // Create a pattern to match for the "\"
                    Pattern p = Pattern.compile("\\\\");
                    // Create a matcher with an input string
                    Matcher m = p.matcher(current_line);
                    boolean beginning_of_record = m.find();
                    if (beginning_of_record) {
                        line_number = 0;
                        number_of_records++;
                    } else {
                        line_number++;
                    if ( (line_number == 2) && (current_line.length() != 0) ) {
                        snomedCodes = current_line;
                        System.out.println(snomedCodes);
                        complete_records.add(current_line);
            catch (FileNotFoundException ex) {
                ex.printStackTrace();
            catch (IOException ex){
                ex.printStackTrace();
            finally {
                try {
                    if (input!= null) {
                        input.close();
                catch (IOException ex) {
                    ex.printStackTrace();
            return complete_records;
        static public void setContents(File reformatFile, ArrayList<String> snomedCodes)
                                     throws FileNotFoundException, IOException {
           Writer output = null;
            try {
                output = new BufferedWriter( new FileWriter(reformatFile) );
                  for (String index : snomedCodes) {
                      output.write( snomedCodes.toString() );
            finally {
                if (output != null) output.close();
        static public void printContents(File existingFile) {
            StringBuffer contents = new StringBuffer();
            BufferedReader input = null;
            int line_number = 0;
            int number_of_records = 0;
            String snomedCodes = null;
            try {
                input = new BufferedReader( new FileReader(existingFile) );
                String current_line = null;
                while (( current_line = input.readLine()) != null)
                    System.out.println(current_line);
            catch (FileNotFoundException ex) {
                ex.printStackTrace();
            catch (IOException ex){
                ex.printStackTrace();
            finally {
                try {
                    if (input!= null) {
                        input.close();
                catch (IOException ex) {
                    ex.printStackTrace();
        public static void main (String args[]) throws IOException {
            File currentFile = new File("D:\\dummy_patient.txt");
            allRecords = getContents(currentFile);
            File snomedFile = new File( "D:\\Snomed-Codes.txt");
            setContents(snomedFile, allRecords);
            printContents(snomedFile);
    }There are 4 patient records in the dummy_patient.txt file but only the 1st (M44110|T33010) & 3rd (M92603|T10350) records have results in them. The 2nd & 4th records have blank results.
    Lastly, could someone explain to me the difference between java.util.List & java.util.ArrayList?
    I am running Netbeans 5.0, jdk1.5.0_09 on Windows XP, SP2.
    Many thanks,
    Netbeans Fan.

    while (snomedCodes.iterator().hasNext())
      output.write( snomedCodes.toString() );
    }Here you have some kind of a list or something (I couldn't stand to read all that unformatted code but I suppose you can find out). It has an iterator which gives you the entries of the list one at a time. You keep asking if it has more entries -- which it does -- but you never get those entries by calling the next() method, so it always has all the entries still available.
    And your code inside the loop is independent of the iterator, so it's rather pointless to iterate over the entries and output exactly the same data for each entry. Even if you were iterating correctly.

  • [CS3 JS]  Reading TXT file content into String

    Hello,
    I'm currently wanting to display a dialog box that has a dropdown menu containing all countries of the world.
    I have an external txt file that contains a list of all countries.
    I thought I would simply read-in the contents of the 'txt' file into a string and use it for displaying the list.
    For example
    i Instead of the usual:
    > var myLandMenu = dropdowns.add({stringList:["A", "B"...], selectedIndex:0});
    i I thought of doing something like:
    > var myLandList = ....? HELP ?....
    > var myLandMenu = dropdowns.add({stringList:myLandList, selectedIndex:0});
    Is this the way to do it?
    What would be the way to read in the text file content as a string?
    Thanks in advance,
    Lee

    > var myLandList = ....? HELP ?....
    > var myLandMenu = dropdowns.add({stringList:myLandList, selectedIndex:0});
    It's hard to tell from context, but myLandList needs to be an array of strings.
    If the file has one element per line, this would be one way of handling the
    conversion:
    var file = File("~/countries.txt");
    file.open("r");
    var str = file.read();
    file.close();
    var myLandList = str.split(/[\r\n]+/);
    And assuming that this is ScriptUI and not the older ID UI, the menu creation
    would look more like:
    var myLandMenu = dropdowns.add(bounds, myLandList);
    myLandMenu.items[0].selected = true;
    -X
    for photoshop scripting solutions of all sorts
    contact: [email protected]

  • How to store content of file in a string

    Hi All :) ,
    i wanted to store all the content of a file say HTML file in a String ,please tell me how should i do that so that all the content from <HTML> to </HTML> copied to the string ..thanks :)

    ashish.escape wrote:
    Is this a right way ?It's not a good way, but I think that it will almost work. To make it work, try using a BufferedReader instead of a DataInputStream (which is deprecated for reading lines), like this:
    BufferedReader reader = new BufferedReader( new InputStreamReader( fis ) );
    while( (thisLine = reader.readLine() ) != null )
    ...Don't forget to close the reader after you're done.
    There are quite a few things "not good" about this code:
    * The exception handling is horrid - you may very well be hiding the real problem - try getting rid of the try/catch and simply declare your main method as 'public static void main(String[] args) throws Exception' - that will exit the application and print the full exception and stack trace to the console. I would make this change and run the application again before doing anything else.
    * Use a StringBuffer to append to, concatenating Strings is very slow.
    * It's not apparent why you even need to read a line at a time - it looks like you could just read the file into a buffer and append that to the StringBuffer without needing to worry about parsing it a line at a time, unless there is some processing that you're doing on each line that is not shown in this code snippet.
    As the first responder said, you should really read the IO tutorial here:
    http://java.sun.com/docs/books/tutorial/essential/io/

  • Conversion of byte into string

    how can we convert byte into string???
    would u plzz help me??

    It depends on what relationship you want between byte and string. Is the string the numeric representation or the character value?
    byte b = (byte)65;
    String s1 = String.valueOf(byte); // gives "65"
    String s2 = new String(new byte[]{b}, "ISO-8859-1");  // gives "A"

  • How can u get the matching percentage whenever compare the pdf files(compare the strings)

    Actually I want matching percentage whenever compare the pdf files.First I had completed 
    read the pdf files content into string
    my code like as
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using iTextSharp.text.pdf.parser;
    namespace WindowsFormsApplication1
    public partial class Form1 : Form
    string str1;
    string filename;
    string path;
    string str2;
    public Form1()
    InitializeComponent();
    private void button1_Click(object sender, EventArgs e)
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.CheckFileExists = true;
    openFileDialog.AddExtension = true;
    openFileDialog.Filter = "PDF files (*.pdf)|*.pdf";
    DialogResult result = openFileDialog.ShowDialog();
    if (result == DialogResult.OK)
    filename = Path.GetFileName(openFileDialog.FileName);
    path = Path.GetDirectoryName(openFileDialog.FileName);
    textBox1.Text = path + "\\" + filename;
    private void button2_Click(object sender, EventArgs e)
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.CheckFileExists = true;
    openFileDialog.AddExtension = true;
    openFileDialog.Filter = "PDF files (*.pdf)|*.pdf";
    DialogResult result = openFileDialog.ShowDialog();
    if (result == DialogResult.OK)
    filename = Path.GetFileName(openFileDialog.FileName);
    path = Path.GetDirectoryName(openFileDialog.FileName);
    textBox2.Text = path + "\\" + filename;
    public static string ExtractTextFromPdf(string filename)
    using (PdfReader r = new PdfReader(filename))
    StringBuilder text = new StringBuilder();
    for (int i = 1; i <= r.NumberOfPages; i++)
    text.Append(PdfTextExtractor.GetTextFromPage(r, i));
    string result = text.ToString();
    return result;
    public static string Extract(string filename)
    using (PdfReader r = new PdfReader(filename))
    StringBuilder text = new StringBuilder();
    for (int i = 1; i <= r.NumberOfPages; i++)
    text.Append(PdfTextExtractor.GetTextFromPage(r, i));
    string result1 = text.ToString();
    return result1;
    private void button3_Click(object sender, EventArgs e)
    str1 = Form1.ExtractTextFromPdf(textBox1.Text);
    str2 = Form1.Extract(textBox2.Text);
    }Finally how can u get the matching percentage whenever compare the pdf files(compare the strings)please help me.thank u

    Hi,
    Based on your code, I see your code related to
    iTextSharp Pdf.
    iText is a third party library to create PDF originally written for java. iTextSharp is
    the C# adaptation of that library.
    Question regarding iText are better asked on the iText forum, rather than the Microsoft Forum:
    http://itextpdf.com/support
    Thanks for your understanding.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Set encoding to read a file into a string

    in my Coding i Want to read a file into a string like this
    File myFile = new File (Dateipfad);
            System.out.println("folgende Datei wird nun verarbeitet: " + Dateipfad);
             java.io.BufferedReader myBis = new java.io.BufferedReader(new java.io.FileReader(myFile.getAbsolutePath()));
      myBis.StringBuffer buf = new StringBuffer();
             String line = myBis.readLine();
             while (line != null)
                    buf.append(line);
                    line = myBis.readLine();
      myBis.close();
    ] now i just want to set an encoding "ISO-8859-1", so that all �`s, �`s or �`s dont get lost.
    Can Anyone help me please ?!

    You must use java.io.InputStreamReader to set the required encoding.
    See the API for more details.
    http://java.sun.com/j2se/1.3/docs/api/java/io/InputStreamReader.html
    HTH,
    Manuel Amago.

  • Strange file called masterNames.strings launches xcode at startup

    I've just upgraded my hard drive to 640GB and duplicated the previous 500GB hard drive with SuperDuper. Everything seems like how it is supposed to be, except that xcode launches this strange file called "masterNames.strings" when I start the machine. Below is the content of the file.
    "Title & Bullets - Right" = "标题与项目符号 - 右对齐";
    "Title - Top" = "标题 - 顶部对齐";
    "Bullets" = "项目符号";
    "Title - Center" = "标题 - 居中";
    "Title, Bullets & Photo" = "标题、项目符号与照片";
    "Blank - Ornamental Border" = "空白 - 装饰边框";
    "Title & Bullets" = "标题与项目符号";
    "Title & Bullets - Left" = "标题与项目符号 - 左对齐";
    "Blank" = "空白";
    "Photo - 3 Up" = "照片 - 3 联";
    "Title & Bullets - 2 Column" = "标题与项目符号 - 2 栏";
    "Photo - Vertical" = "照片 - 垂直";
    "Title & Subtitle" = "标题与副标题";
    "Photo - Horizontal" = "照片 - 水平";
    Apparently it's in Chinese but Chinese is not at all the language I've set up the OS with. I use U.S. English. I do not know where this file came from. I've repaired permissions using Maintenance but it doesn't seem to fix it.
    I've googled around to see if anyone has experienced a similar problem and found one (and only one) that looks strikingly similar to my issue, except that the language is Portuguese for him. Here's the link to that thread. It was two years ago and doesn't look like it was solved.
    http://discussions.apple.com/thread.jspa?threadID=1800575
    Could somebody please help me? This is pretty annoying.

    Open Accounts preferences and click on the Login Items tab. If you see that file in the list then select it and click on the Delete [-] key.
    Consider otherwise that your clone is not good unless it's also happening on the drive you replaced.

  • Byte to String conversion for encryption and decryption

    Hi Friends ,
    I am trying to encrypt a password string and then decrypt it .
    The thing is i need to convert the encrypted String which is a byte array to a string . While decrypting i need to convert the encrypted string to a Byte .
    I tried using String.getBytes() for converting a string to byte array , but this is giving an exception
    javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipherPlease find below my code
    import java.security.Key;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;
    * @author rajeshreddy
    public class Encrypt
        public static void main(String[] args)
            try
            BASE64Encoder en = new BASE64Encoder();
            BASE64Decoder en1 = new BASE64Decoder();
                String password = "S_@!et";
                KeyGenerator kg = KeyGenerator.getInstance("DESede");
                Key key = kg.generateKey();
                Cipher cipher = Cipher.getInstance("DESede");
                cipher.init(Cipher.ENCRYPT_MODE, key);
                // Encrypt password
                byte[] encrypted = cipher.doFinal(password.getBytes());
                String e = new String(encrypted);
                byte[] toDecrypt  = e.getBytes();
                // Create decryption cipher
                cipher.init(Cipher.DECRYPT_MODE, key);
                byte[] decrypted = cipher.doFinal(toDecrypt);
                // Convert byte[] to String
                String decryptedString = new String(decrypted);
                System.out.println("password: " + password);
                System.out.println("encrypted: " + encrypted);
                System.out.println("decrypted: " + decryptedString);
            } catch (Exception ex)
                ex.printStackTrace();
    }I cab use sun.misc.BASE64Decoder and sun.misc.BASE64Encoder which avoids this error, but this packages are sun proprietery packages so there is a chance of removing these in future releases.
    Please suggest me the best way to tackle this

    1) The "Jakarta Commons Codec" project has Base64 and Hex encoders that are well tested and well regarded. Google is your friend.
    2) Since this is a new project, you should use AES rather than DESede.
    3) The defaults when generating the Cipher object using
    Cipher cipher = Cipher.getInstance("DESede");
                is for ECB block mode with PKCS5 padding. ECB is not a good block mode since it allows some limited forgery though splicing of ciphertext. Use one of the feedback modes such as CBC.
    4) Why are you encrypting passwords rather than just hashing them? While there are situations where encryption rather than hashing is required, it is not the norm and does normally require justification.
    5) Converting encrypted or hashed data to a String is not normally required. What are you doing with that requires this?
    Edited by: sabre150 on Dec 29, 2008 7:44 AM

  • How could I delete files with name string with "TAL" and older than 05.05.

    How could I delete files with name string with "TAL" and older than 05.05.2009 on unix

    Our ECC Ides system today was not responsible. For first time 17 users were working on the systtem (IWN2008/SQL2005 based). Before the people were maximally 5.
    The server is done by making a homogeneous system copy from an blade machine(now it is an VIrTUAL)
    There was enaught disk space. However I checked Wokload 03sdn transaction) inn system. and found out that at that time of restarting(I had to restart system 3 times to get logged on the system and even then it was almost unresponsive.
    I can found in there top abap."Login_Pw", "SESSION_MANAGER", "?". (BAtch), "ADMSBUF, >DEleyed Function call, RSPOWPOO""RSWWclear", ""VA01", "SAPMHHTP  "Buf  Sync" >DDLOC CLEANUP)""rsbtctE"
    What can I do?
    ¸
    Who could interfer SAP_CCMS_MONI_BATCH_DPSAP_CCMS_MONI_BATCH_DP
    the 2 main users under users profile were ZUGTIN running and SAPSYS( running many system jobs)
    How to approach the problem

Maybe you are looking for