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

Similar Messages

  • How to read\write text file into oracle database.

    Hello,
    I am having text file called getInfo in c:\temp folder. I would like to populate data from text file to data base. How to proceed. Could anybody help me out.
    Thanks,
    Shailu

    Here is a web page with easy to follow instructions regarding external files: http://www.adp-gmbh.ch/ora/misc/ext_table.html.
    Now I understand what all the excitement is over external tables.
    "External tables can read flat files (that follow some rules) as though they were ordinary (although read-only) Oracle tables. Therefore, it is convenient to use external tables to load flat files into the DB." -from the above link.

  • 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-Talk

         public 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.

  • How to read from text file?

    I would like to read data (frequencies) already written in a text file. I will need read these frequencies one at a time to set the function generator (as part of my data acquisition application), acquire data that is in turn written to a file and then go back and read the next frequency from the file to repeat the process again. I also have another idea of doing the same, which is read all the frequencies from the text file and populate a table and a frequency value is picked from the table each time to go through the process mentioned above.
    Can anyone suggest the following: (1) How to read from a text file, (2) What could be the most efficient way of solving my above problem.
    I am a new LabVIEW user and any help will be appreciated.

    Hi Research,
    Depending on the format of the data file, there are a few options for reading it.  If it is tab delimited, you may want to use the Read from SpreadSheet File VI which will read the file into an Array.  You can then use the Index Array VI to pull out individual entries.  If the files is ASCII but not tab delimited, you could use the regular Open File and Read File VIs.  You can either read the file out piece by piece, or read the entire file into a string and then use the Match Pattern VI to parse out the different elements (there are actually many ways to do this - check out the Strings subpalette). 
    Since you're new to LabVIEW, you may want to check out these resources:
    Three Hour Introduction to LabVIEW
    Six Hour Introduction to LabVIEW
    Getting Started with LabVIEW
    I hope this helps!  Let us know if you have more questions,
    Megan B.
    National Instruments

  • How can I sync text files into iPhone?

    How can I sync text files into iPhone? like doc. txt. for reading or editing

    The native iPhone OS doesn't allow that. I think there are several solutions to this, some of which may be against the AT&T or Apple rules. One legitimate solution is The Missing Sync for iPhone by mark/space (http://www.markspace.com).
    Before I had an iPhone, I owned a copy of The Missing Sync for Windows Mobile. It was a pretty decent app. In my opinion, though, their app for the iPhone is NOT worth the price ($40 new, $25 for a cross-grade).
    Also, check the App Store (if you have 2.0 software)--there may be an app that does this, probably for a lot less $.

  • How to read several text files at a time

    Dear all
          Read and write one text file is not a problem, but  what confusies me is how to read several text files at one time, in the meanwhile,
    is it possible to display the name of the text file?
    For example, assuming I want to load file" cha 1, cha 2 , cha 3, " at one time and show their names, how to hadle with it
    I have reviewed some files and it is not helpful

    Either with a 'for' loop like in the lib you have attached, or like this attached VI
    that's it
    Message Edited by devchander on 05-30-2006 05:11 AM
    Attachments:
    MULTIPLE READ.vi ‏44 KB

  • How to read a text file through pl/sql

    How to read a text file through pl/sql

    pl/sql runs inside the database. so your file also should be on the database server file system for you to be able to read.
    check out UTL_FILE package. This is the database package to read/write files on the database server.

  • Open and read from text file into a text box for Windows Store

    I wish to open and read from a text file into a text box in C# for the Windows Store using VS Express 2012 for Windows 8.
    Can anyone point me to sample code and tutorials specifically for Windows Store using C#.
    Is it possible to add a Text file in Windows Store. This option only seems to be available in Visual C#.
    Thanks
    Wendel

    This is a simple sample for Read/Load Text file from IsolateStorage and Read file from InstalledLocation (this folder only can be read)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Storage;
    using System.IO;
    namespace TextFileDemo
    public class TextFileHelper
    async public static Task<bool> SaveTextFileToIsolateStorageAsync(string filename, string data)
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    try
    using (var s = await file.OpenStreamForWriteAsync())
    s.Write(fileBytes, 0, fileBytes.Length);
    return true;
    catch
    return false;
    async public static Task<string> LoadTextFileFormIsolateStorageAsync(string filename)
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    async public static Task<string> LoadTextFileFormInstalledLocationAsync(string filename)
    StorageFolder local = Windows.ApplicationModel.Package.Current.InstalledLocation;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    show how to use it as below
    async private void Button_Click(object sender, RoutedEventArgs e)
    string txt =await TextFileHelper.LoadTextFileFormInstalledLocationAsync("TextFile1.txt");
    Debug.WriteLine(txt);
    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

  • 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>
    Thanks

    Sorry, 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?

  • Convert a line read from text file into string

    how to convert a line from text file into string?
    i know how to convert to numbers,
    private int  parseLine1(String line) {
              StringTokenizer tokenizer = new StringTokenizer(line);
                  value1 = Integer.valueOf(tokenizer.nextToken()).intValue();
                  value2 = Integer.valueOf(tokenizer.nextToken()).intValue();
                 return value1;
                     }but what about charactrs?

    ok, here is my problem, i have a file with a bunch of Xs in it but position function doesn't return a correct value, what's going wrong?
    private int positioni(){
           int i=0;
           int j=0;
           int b=0;
           String line="";
            while(line!= null){
                for(int a=0; a<line.length(); a++){
                    if(line.charAt(a)=='X'){
                        i=a;}
                b++;
                j=b;
                t=line.length();
                line=read(gridFileN);
           return i;
    private String read(String ggridFileN){
             TextStreamReader ggridFile = new TextStreamReader(ggridFileN);
             return ggridFile.readLine();

  • How to Read the "text file and csv file" through powershell Scripts

    Hi All
    i need to add a multiple users in a particular Group through powershell Script how to read the text and CSV files in powershell
    am completly new to Powershell scripts any one pls respond ASAP.with step by step process pls
    Regards:
    Rajeshreddy.k

    Hi Rajeshreddy.k,
    To add multiple users to one group, I wouldn't use a .csv file since the only value you need from a list is the users to be added.
    To start create a list of users that should be added to the group, import this list in a variable called $users, the group distinguishedName in a variable called $Group and simply call the ActiveDirectory cmdlet Add-GroupMember.
    $Users = Get-Content -Path 'C:\ListOfUsernames.txt'
    $Group = 'CN=MyGroup,OU=MyOrg,DC=domain,DC=lcl'
    Add-ADGroupMember -Identity $Group -Members $Users

  • How to read any text files using file adapter as it is

    Hi,
    I need to build bpel process to read any text files as it is.I am file adapter and using opaque schema.But input file is coming as base64encoding format.But i need the input as it is.How can i do that.
    Is there any sample schema to read input text files as it is?

    in java embedding activity i need to remove all newlines from my input text file.During this process i am getting arryindexoutofbounds exception.Below is my code
    String input = (String)getVariableData("inputFileStr");
    Base64Decoder Decoder = new Base64Decoder();
    try
    String decoded = Base64Decoder.decode(input); --exception is coming at this line
    setVariableData("inputFileStr", decoded);
    decoded = decoded.replaceAll("\\n|\\r", "");
    byte[] outputBytes = decoded.getBytes();
    String reencoded = Base64Encoder.encode(outputBytes);
    setVariableData("outputFileStr", reencoded);
    catch(Exception uee)
    uee.printStackTrace();
    below is stack trace:
    09/02/26 08:10:33 java.lang.ArrayIndexOutOfBoundsException: -1
    09/02/26 08:10:33 at com.collaxa.common.util.Base64DecoderStream.decode(Base64DecoderStream.java:162)
    09/02/26 08:10:33 at com.collaxa.common.util.Base64DecoderStream.decode(Base64DecoderStream.java:143)
    09/02/26 08:10:33 at com.collaxa.common.util.Base64Decoder.decode(Base64Decoder.java:36)

  • How to read a text file through BufferedReader

    I want to read a text file by BufferedReader, How can I do that? The format of the file as follows:
    NAME MAKER YEAR PRICE CONDITION
    13 Dead End Drive __ Milton Bradley 1993 $22.00 C09
    18 Wheeler Fever __ Donna Lee Ent. 1980 $20.00 C09
    how to parse the line from the file to extract the name, maker, year, price and condition.
    Thank you first.

    Look at: stream tutorials,
    BufferedReader, InputStreamReader, FileInputStream, StringTokenizer

  • How to read a text file and write text file

    Hello,
    I have a text file A look like this:
    0 0
    0 A B C
    1 B C D
    2 D G G
    10
    1 A R T
    2 T Y U
    3 G H J
    4 T H K
    20
    1 G H J
    2 G H J
    I want to always get rid of last letter and select only the first and last line and save it to another text file B. The output should like this
    0 A B
    2 D G
    1 A R
    4 T H
    1 G H
    2 G H
    I know how to read and write a text file, but how can I select the text when I am reading a text file. Can anyone give me an example?
    Thank you

    If the text file A look like that
    0 0
    0 3479563,41166 6756595,64723 78,31 1,#QNAN
    1 3479515,89803 6756588,20824 77,81 1,#QNAN
    2 3479502,91618 6756582,6984 77,94 1,#QNAN
    3 3479516,16334 6756507,11687 84,94 1,#QNAN
    4 3479519,14188 6756498,54413 85,67 1,#QNAN
    5 3479525,61721 6756493,89255 86,02 1,#QNAN
    6 3479649,5546 6756453,21824 89,57 1,#QNAN
    1 0
    0 3478762,36013 6755006,54907 54,8 1,#QNAN
    1 3478756,19538 6755078,16787 53,63 1,#QNAN
    2 0
    3 0
    N 0
    I want to read the line that before and after 1 0, 2 0, ...N 0 line to arraylist. I have programed the following code
    public ArrayList<String>save2;
    public BufferedWriter bufwriter;
    File writefile;
    String filepath, filecontent, read;
    String readStr = "" ;
    String[]temp = null;
    public String readfile(String path) {
    int i = 0;
    ArrayList<String> save = new ArrayList <String>();
    try {
    filepath = "D:\\thesis\\Material\\data\\CriticalNetwork\\test3.txt";
    File file = new File(filepath);
    FileReader fileread = new FileReader(file);
    BufferedReader bufread = new BufferedReader(fileread);
    this.read = null;
    // read text file and save each line content to arraylist
    while ((read = bufread.readLine()) != null ) {
    save.add(read);
    // split each arraylist[i] element by space and save it to String[]
    for(i=0; i< save.size();i++){
    this.temp = save.get(i).split(" ") ;
    // if String[] contain N 0 such as 0 0, 1 0, 2 0 then save its previous and next line from save arraylist to save2 arraylist
    if (temp.equals(i+"0")){
    this.save2.add(save.get(i));
    System.out.println(save2.get(i));
    } catch (Exception d) {
    System.out.println(d.getMessage());
    return readStr;
    My code has something wrong. It always printout null. Can anyone help me?
    Best Regards,
    Zhang

  • How to upload the text file into smart forms

    Hi Experts,
    can any one tell me that how to upload  the text file or html file to SAP Script form or smart forms
    i have download the form info from SAPscript form.to text file.
    now i want to upload the text file to smartforms.
    is it possible ? if it is possible, then how can i do that ?
    Thanks in Advance.
    Regards,
    Mani

    <b>For Scripts</b>
    Go to SE38. Put in the program name RSTXSCRP. Execute it.
    Mode(Export/Import) : Import.
    Give the file name from which you want to upload and execute it.
    <b>For Smartforms</b>
    TCode : smartforms.
    Give the form name.
    Utilities-->Upload form.
    Reward points if helpful.
    Thanks
    Aneesh.

Maybe you are looking for