A simple text file in a StringBuffer

Hello ,
I am new in Java. I want to read a file and put it in a StringBuffer so the entire file can be edited as a simple bunch string. How to process efficiently ??
Thanks for help

java.io.BufferedReader in = new java.io.BufferedReader( new java.io.FileReader( "yourfile.txt" ) );
StringBuffer buff = new StringBuffer();
String line = null;
while((line = in.readLine())!=null)
buff.append(line);
in.close();
System.out.println( "Contents of file: " + buff.toString() );

Similar Messages

  • Reading a text file into a StringBuffer?

    Hey all,
    I've taken a year of Java programming class so far, but I doubt my class is ever going to get in to things like this. I've been trying to develop a program that reads a small text file into a StringBuffer for manipulation and use in the program. I've been looking around the web, but thus far all I've seen are things like FileInputStream, in the java.io.* package; nothing about StringBuffers.
    And I'm pretty sure it's kind of hard, too. If someone could give me a simple(?) explanation, or a link to a tutorial that shows you this or something, it would be much appreciated.
    Also, is it possible to pull an integer out of a string? I was just wondering this, I don't think you can cast a string to an int or anything. Ha ha.
    ~Darkslime, Java student

    Hey all,
    I've taken a year of Java programming class so far,
    but I doubt my class is ever going to get in to
    things like this. I've been trying to develop a
    program that reads a small text file into a
    StringBuffer for manipulation and use in the program.
    I've been looking around the web, but thus far all
    I've seen are things like FileInputStream, in the
    java.io.* package; nothing about StringBuffers.
    And I'm pretty sure it's kind of hard, too. If
    someone could give me a simple(?) explanation, or a
    link to a tutorial that shows you this or something,
    it would be much appreciated.
    Also, is it possible to pull an integer out of a
    string? I was just wondering this, I don't think you
    can cast a string to an int or anything. Ha ha.
    ~Darkslime, Java student
    try {
            BufferedReader in = new BufferedReader(new FileReader("infilename"));
            String str;
            while ((str = in.readLine()) != null) {
                process(str);
            in.close();
        } catch (IOException e) {
        }

  • Cannot print a simple Text File

    Hello All,
    I wrote the following program
    import java.io.*;
    import java.awt.print.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    public class TestPrint
         public static void main(String[] args) throws Exception
              FileInputStream fis = new FileInputStream(new File("pds.txt"));
              byte[] fileByte = new byte[34];
              int read = 0;
              int counter = 0;
              while((read = fis.read()) != -1)
                   fileByte[counter++] = (byte)read;
              PrintService services[] = PrinterJob.lookupPrintServices();
              DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII;
              PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
              aset.add(MediaSizeName.ISO_A4);
              aset.add(new Copies(1));
              Doc doc = new SimpleDoc(fileByte, flavor, null);
              DocPrintJob pj = services[0].createPrintJob();
              pj.print(doc, aset);
    }The file I am trying to print is a simple text file. My requirement is to convert it to an array of bytes and then print it.
    However I get the exception
    Exception in thread "main" java.lang.IllegalArgumentException: data is not of de
    clared type
    at javax.print.SimpleDoc.<init>(Unknown Source)
    at TestPrint.main(TestPrint.java:25)
    Please help me. I would appriciate any help in this matter.
    regards,
    Abhishek.
    PS: The contents of the file (pds.txt) which I am trying to print is
    PDS
    pds
    pds
    pds
    pds

    Hi,
    you get a java.lang.IllegalArgumentException in line 25:
    So we take the Java API for SimpleDoc:
    IllegalArgumentException - if flavor or printData is null, or the printData does not correspond to the specified doc flavor--for example, the data is not of the type specified as the representation in the DocFlavor.
    Since fileByte seems not the be null, the type must be wrong!
    In line 21 we see:
    DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_US_ASCII;
    so fileByte must be type java.io.InputStream, which it isn�t. This causes your IllegalArgumentException.
    So try in line 21:
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.TEXT_PLAIN_US_ASCII;
    Let me know if that was the reason!
    Best regards
    Martin

  • High Score Table: Writing a Simple Text File with Flash and PHP

    I am having a problem getting Flash to work with PHP as I need Flash to read and write to a text file on a server to store simple name/score data for a games hi score table. I can read from the text file into Flash easily enough but also need to write to the file when a new high score is reached, so I need to use PHP to do that. I can send the data from flash to the php file via POST but so far it is not working. The PHP file is confirmed as working as I added an echo to the file which displayed a message so I  could check that the server was running PHP - the files were also uploaded to a remote server so I  could test them properly. Flash code is as follows:
    //php filewriter
    var myLV = new LoadVars();
    function sendData() {
    //sets up variable 'hsdata' to send to php
    myLV.hsdata = myText;
    myLV.send("hiscores.php");
    I believe this sends the variable 'myText' to the php file as a variable called 'hsdata' which I want the php file to write into a text file. The mytext variable is just a long string that has all the scores and names in the hiscore. OK, XML would be better way of doing this but for speed I just want to get basic functionality working, so storing a simple text sting is adequate for now. The PHP code that reads the Flash 'hsdata' variable and writes it to the text file 'scores.txt' follows:
    <?php
    //assigns to variable the data POSTed from flash
    $flashdata = $_POST["hsdata"];
    //file handler opens file and erases all contents with w arg
    $fh = fopen("scores.txt","w");
    //adds data to file
    fwrite ($fh,$flashdata);
    //closes file
    fclose ($fh);
    echo 'php file is working';
    ?>
    Any help with this would be greatly appreciated - once I can get php to write simple text files I should be ok. Thanks.

    Thanks for your help.
    I have got Flash working to a certain extent with PHP using loadVars but have been unable to get flash to receive a variable declared in PHP. Here's my Flash code:
    var outLV = new LoadVars();
    var inLV = new LoadVars();
    function sendData() {
    outLV.hsdata = "Hello from Flash";
    outLV.sendAndLoad("http://www.mysite.com/hiscores/test23.php",inLV,"post");
    inLV.onLoad = function(success) {
    if (success) {
      //sets dynamic text box to show variable sent from php
      statusTxt.text = phpmess;
    } else {
      statusTxt.text = "No Data Received";
    This works ok and the inLV.onLoad function reports that it is receiving data but does not display the variable received from PHP. The PHP file is like this:
    <?php
    $mytxt =$_POST['hsdata'];
    $myfile = "test23.txt";
    $fh = fopen($myfile,'w');
    //adds data to file
    fwrite($fh, $mytxt);
    //closes file
    fclose ($fh);
    $mess = "hello there from php";
    echo ("&phpmess=$mess&");
    ?>
    The PHP file is correctly receiving the hsdata from flash and writing it to a text file, but there seems to be a problem with the final part of the code which is intended to send a variable called 'phpmess' back to Flash, this is the string "hello there from php". How do I set up Flash and PHP so that PHP can send a variable back to Flash using echo? Really have tried everything but am totally baffled. Online tutorials have given numerous different syntax configurations for how the PHP file should be written which has really confused me - any help would be greatly appreciated.

  • Mail Adapter: How to send data as a simple text file attachment?

    Hi All
    I have a proxy to file scenario, where i write data to a text file.
    Now, i need to have a second receiver. I have to send an email, with the above file as an attachment, to this receiver.
    How can i do this?
    How can i send the data as a text file attachment to the receiver?
    Many Thanks
    Chandra

    Hi,
    To send the message to the second receiver you need to have:
    1) Necessary mail message format (can download from service marketplace)
    2) Receiver mail communication channel.
    3) Create the necessary Configuration Objects .... Receiver Determination, Interface Determination, Receiver Agreement.
    3) You can do a XSLT mapping (if required)....if no complex logic is needed then you can do a simple Message mapping.
    4) In the receiver CC make sure that you check the Adapter Specific Message Attribute checkbox.
    For more info you can refer my answer in this thread:
    Re: xml in mail
    Also refer the blog:
    /people/michal.krawczyk2/blog/2005/11/23/xi-html-e-mails-from-the-receiver-mail-adapter
    Regards,
    Abhishek.

  • How to read a String from a simple text file.

    I have a set up popup reminders, the content of which I have entered into a text file. I read the text and display it in a specially formatted JFrame/JPanel.
    My question is, since readLine() has been deprecated, how do you read a simple line of text data from a file created by, say, notepad? I guess I could just use readLine() anyway, but I want to learn the language, and "playing by the rules" seems to be the way I should go.

    I''m guessing your referring to the readLine method of DataInputStream. Use another class, like BufferedReader, which also happens to have a method named readLine:
    BufferedReader in = new BufferedReader(new FileReader(filename));
    try {
        String line;
        while ((line = in.readLine()) != null) {
            //process line
    } finally {
        in.close();
    }

  • Reading a simple text file..

    Hi,
    can somebody point me to an example please?
    I have a file like below. I want to read LINE-by-LINE and do some
    operation on every line and then next...
    100000;32755;-31412;-30342;28086
    100000;32755;-31389;-30324;28041
    TIA

    I think you might be better off reading the entire file at once with Read From spreadsheet File and then manipulating the resulting 2D array, but if you want to do it line by line then a good place to start is the Read Lines From File function on the File I/O palette. Inside of this is a case structure and case 2 reads one line at a time for x number of lines or until EOF is found.

  • Java write/append to each line of a text file

    I have spent numerous hours trying to figure out what I am doing wrong. If anyone more experienced could tell me what is wrong with my code.
    I have a very simple text file with 5 lines:
    line1
    line2
    line3
    line4
    line5
    All I am trying to do is append some string to the end of each of those lines. Everytime I run my code, it erases all content but does not write/append anything to the file. Any help is greatly appreciated.
    Thanks! I am about to throw this monitor out the window!!
    package Chapter6;
    import java.io.*;
    public class fileNavigation2 {
         public static void main(String[] args) {
              File dir = new File("C:\\testing");
              System.out.println(dir.isDirectory());
              try {
                   File file = new File(dir, "Test.txt");
                   FileReader fr = new FileReader(file);
                   BufferedReader br = new BufferedReader(fr);
                   FileWriter fw = new FileWriter(file);
                   BufferedWriter bw = new BufferedWriter(fw);
                   String s = "Add1,";
                   String s2 = "Add2\n";
                   String str;
                   while((str = br.readLine()) != null) {
                   StringBuffer sb = new StringBuffer(str);
                   sb.append(s + s2);
                   String y = sb.toString();
                   System.out.println(sb);
                   System.out.println("Appending");
                   bw.write(y);
                   bw.close();
                   System.out.println("Done");
              }catch(IOException e) {}
    }

    First, thanks a lot for your feedback. The code makes a lot of sense but it does not update the content of my Test.txt file.
    I only edited the line of code that creates the new file so that it could find the location of the file.
    Scanner file = new Scanner(new File("C:\\testing",fileName));==============================
    The code now looks like:
    import java.io.*;
    import java.util.*;
    public class Main {
        static void appendTo(String fileName, String[] newLines) throws IOException {
            List<String> allLines = getLinesFrom(fileName);
            for(String line : newLines) {
                allLines.add(line);
            writeLinesTo(fileName, allLines);
        static List<String> getLinesFrom(String fileName) throws IOException {
            List<String> lines = new ArrayList<String>();
            Scanner file = new Scanner(new File("C:\\testing",fileName));
            while(file.hasNextLine()) {
                lines.add(file.nextLine());
            file.close();
            System.out.println(lines);
            return lines;
        static void writeLinesTo(String fileName, List<String> lines) throws IOException {
            BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
            for(String line : lines) {
                out.write(line);
                out.write(System.getProperty("line.separator"));
            out.close();
        public static void main(String[] args) {
            String fileName = "Test.txt";
            String[] extraLines = {
                    "a new line",
                    "and yet another new line"
            try {
                appendTo(fileName, extraLines);
                System.out.println("Done.");
            } catch (IOException e) {
                e.printStackTrace();
    }Again, thanks for the help.

  • Print Text File in NW 3.12?

    I have to admit some ignorance regarding NetWare printing, so my
    apologies in advance...
    I work for a document management company, and am trying to find a
    solution for a customer running a fairly archaic, DOS 6.22-based
    application that utilizes a NetWare 3.12 server for file and print
    services. My need is to retrieve print output from their application,
    in the form of a text file, and then reprocess it for automated faxing
    through a fax server device.
    My problem is this: their application seems to print directly to a
    printer by defining what it calls a "network port" (which seems to map
    to a spooler, 0 through 5) or LPT1, and by referencing a printer
    definition. As far as I can tell, the files that are deposited in the
    print queue are byte streams, i.e., they're not human-readable (they
    have extra characters that I'm assuming are control characters). They
    therefore aren't usable by my print distribution software.
    I've tried using CAPTURE to send to a text file, but the application
    seems to conflict with the command. If I set CAPTURE, then start the
    application and send a job to LPT1, the application returns an error
    that the printer is unavailable. Upon exiting the application the port
    is no longer being captured (although I've tried all of the options I
    can think of to keep it so). Oddly enough, the application does
    successfully print a text file to LPT2 (for a barcode printer), which
    is CAPTUREd via a command in the system autoexec.bat. This is done a
    different part of the application.
    If anyone can help me figure out a way to generate a text file in this
    environment, or to work with the print file that's currently being sent
    to the queue (e.g, can it be translated somehow to a simple text file?),
    that would be much, much appreciated. This customer is in a tight spot,
    with an unsupported application that they can't presently afford to
    upgrade. My solution would save them enough money over time to replace
    the system.
    Again, thanks in advance for any help!
    wynand32

    If the Dos app has no print drivers included, then indeed it is relying
    on NW and PRINTDEF/PRINTCON to do the formatting stuff. That must have
    already been set up for it to be successfully printing now, it's just a
    matter of adding a definition that doesn't do anything to the print text.
    >In fact, given my ignorance of the NetWare environment, I'm not sure
    how the term "driver" even applies, unless it would refer to the
    printer definition.
    I was referring to a driver within the Dos app, nothing to do with
    NetWare. For instance Word Perfect for Dos came with Dos drivers for all
    sorts of printers, one of which was a generic text driver.
    >I wonder: is there a setting in PRINTDEF that could be changed for one
    of the printer configs that would influence the output? Or, would
    PRINTCON apply in this environment?
    Not supplied, AFAICS, but either one of the simpler print drivers
    supplied such as Diablo will do, or you'd need to set one up. Hopefully
    http://www.novell.com/documentation/...a/fm19724.html
    will help you enough as it's been too long since I did it to remember
    the details.
    Andrew C Taubman
    Novell Support Forums Volunteer SysOp
    http://support.novell.com/forums
    (Sorry, support is not provided via e-mail)
    Opinions expressed above are not
    necessarily those of Novell Inc.

  • Updating data from a text file in DW is it possible ?

    Hello,
    I would like to know if there is a way to update
    info that I originally input into DW from a .txt file
    using the insert tabular data command.
    If anyone know if this is possible, I'd really appreciate
    knowing this. I don't mean via means of using php, or anything like
    this.
    I am talking about updating info in cells on a local
    computer.
    So for example, a .txt file gets updated, and in turn, DW
    will auto-update the table content it sees in the updated .txt
    file, or other type of data file.
    Thank you for any info

    It really depends on how you've saved the data. If you have a simple text file with x data in one column and y data in another, then you can use the code below. It's just a Read From Spreadsheet File, and Index Array, and Bundle function. Modify as needed for your actual data. If you get stuck, post a small example of your data file.
    Message Edited by Dennis Knutson on 09-17-2008 11:10 AM
    Attachments:
    Read XY Graph.PNG ‏3 KB

  • Plotting data from a text file in LabView 7.1

    This my be a stupid question, but here is goes.  Working with another person, far more LabView experience than I, a VI was created to take data and output it on the screen, real time, as an x-y plot.  Once the test was completed the data was stored in an .txt file which could be read into Excel.  Now the end user wishes to read the old data back into Labview with an x-y plot of the data, the same way it was displayed during the test.  Before I started to pound my head against the wall, thought I would ask this to the group.  Everyone has been very helpful in the pass, so hopefully this will be an easy question for the group.
    The question is how do I import a text file into Labview and plot it on an x-y screen?
    Thanks,
    Scamper

    It really depends on how you've saved the data. If you have a simple text file with x data in one column and y data in another, then you can use the code below. It's just a Read From Spreadsheet File, and Index Array, and Bundle function. Modify as needed for your actual data. If you get stuck, post a small example of your data file.
    Message Edited by Dennis Knutson on 09-17-2008 11:10 AM
    Attachments:
    Read XY Graph.PNG ‏3 KB

  • JSF - Read a text file and diplay lines of text data on the web page

    Hello,
    For one of my projects, I need to display lines of text data on the web page using Java Server Faces Technology. The raw data could be from simple text files or sockets or anything. (Getting the data is not my issue but displaying is). Could anybody send answers with sample code. In servlet, one could do this by -
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException{
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println(DATA);
    out.println(DATA);
    out.println("</html>");
    I am looking for similar solution.
    Thanks in advance
    DK

    Thanks mjolinor.  Works great!
    Two questions.
    1. Could you plz suggest how this could be modified so this code would read the file in or accept it from the pipeline instead of wrapping the (@' around the data?
    2. Could you plz briefly describe some of the details of the code so I can further research and understand.
    Thanks for your help.
    Thanks for your help! SdeDot
    1. It already reads in the file.  The (@' .. '@) bits are just there to create a file using your test data to demonstrate that it works.
    2.  Not user what kind of "details" you want.  There really isn't much there, and get-help on the cmdlets used should provide information on what's going on with them in that script.
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • Reading fields from a text file

    Hi, I'm fairly new to this so bear with me.
    This is for an assignment - the idea is to cretae an online system for booking seats at a cinema - haven't got past the login stage yet?
    I've got an applet that needs to read in a field from a text file.
    I'm using the StringTokenizer function.
    I've put a test in to check that the applet can find the file, which seems to be ok.
    However, it's not reading from the file.
    Te file is a simple text file - fields are seperated by a comma and a space.
    Any ideas?
    Please help as this is quite urgent.
    Prototype Code is below
    public class cinema extends Applet implements ActionListener, ItemListener{
    private List ActionList;
    private int listIndex;
    TextArea t = new TextArea(5, 30);
    private Button gobutton, writebutton, login, logout;
    private PrintWriter suggestfile;
    TextField Userid, password, enterField;
    private int count, checkuser;
    private BufferedReader firstn;
    File myFile = new File("e:\\Ian\\Unistuff\\2nd Year\\se2\\cinema2\\src\\cinema2\\member.txt");
    //Construct the applet
    public cinema() {
    enterField = new TextField("Please enter user ID and Password");
    enterField.setEditable(false);
    add(enterField);
    Userid = new TextField(3);
    add(Userid);
    password = new TextField(10);
    password.setEchoChar('*');
    add(password);
    //Initialize the applet
    public void init() {
    BorderLayout borderLayout1 = new BorderLayout();
    //some code ommitted
    t.setEditable(false);
    add(t);
    gobutton = new Button("Go!");
    add(gobutton);
    gobutton.addActionListener(this);
    public void actionPerformed(ActionEvent event) {
    if (event.getSource() == gobutton) {
    try {
    firstn = new BufferedReader( new FileReader(myFile));
    catch (IOException e) {
    t.setText("Member database missing - please contact Chairperson");
    return;
    try {
    String line1;
    boolean found = false;
    while (( ( line1 = firstn.readLine() ) != null) && (! found))
    {StringTokenizer token1 = new StringTokenizer (line1, " ,");
                              String user = token1.nextToken();
                                 if (Userid.getText().equals(user))
                                   { found = true;
                                     t.setText("Hello");
    firstn.close();
    catch (IOException e) {
    System.err.println("Error Reading File " + myFile + ": " + e.toString());
    Here's the text file:
    Ian, Dodson, 001, rubbish
    Joe, Bloggs, 002, medway
    Bill, Smith, 003, unique
    Guest, , Guest,
    To test that it is working, it should just put a message in the Text Area, but nothing happens when you press the "go" button.

    1. Your applet will not work, because it is trying to
    read file from local disk.
    2. This task can be solved by simple CGI script
    (which is much more common and universal thing than
    java), so you do not need to use java if you want to
    send 3 lines to a server.
    3. See examples and read some books.1. Stated the obvious.
    2. This is a java forum, not Perl.
    3. Pathetic and patronizing.
    Very helpful.

  • How to check a text file is already opened by another process

    Hi All,
      We are facing a requirement to check a simple text file that has been already opened by some other process using java programming.We are using simple file reading concepts to read the content of those text file
      For eg: Let us take sample.txt in any of the system location which is manually opened and we need to check that sample.txt is opened or not using java programming.
                  If it is not opened by any process then only we should  read that file otherwise we shouldn't.
    ANY GUIDANCE WILL BE HELPFUL...
    Thanks & Regards,
    Rumeshbabu

    Hi Christian,
    Thanks. Our scenario is...
    1. We have log files(in.txt) which is scheduled everyday for tracking and the scheduler will be writing the file ,it will be closed by night 11.
    2.So in case if we write any java code to access that log file(using  io file concept in java) we need access to that log file from our standalone java program only after night 11 0 clock.
    3.So we should check a condition whether that log file has been already used by some other process.
    Thanks & Regards.
    Rumeshbabu

  • Brilliant way to create titles from text files

    It was just pointed out to me by a fellow named Greg Hester that there is a way to create titles from a Microsoft Word file using Adobe InDesign. You can create as many titles as you need, and even change text positions around from title to title. Then you export as a PNG.
    If you need to go back and change a color or a font type or size or whatever, you can do that to all of them at once and then just export again. They will automatically update in Premiere Pro.
    I have never even opened InDesign before, and I was able to follow the instructions in this tutorial without a strain.
    The tutorial doesn't show that you can import a frame capture from the video to help position the text, but you can.
    This is very cool. If you subscribe to the Creative Cloud, then you have access to InDesign.

    Best would be to have this template/style functionality in the title tool itself though
    Agreed.
    Remember, all this InDesign thing does is create images that can be used as titles. My Macro created actual titles.
    What really needs to happen is to have a plugin that creates titles from simple text files like the ones created from Notepad, so no Microsoft program is required. The file could have the text, the font style, and many other parameters, and then it could have the time to place the title on the sequence.
    But in the meantime, this InDesign thing seems to be the best we can do for now. If, however, you want to use a fancy font style and it will all be in English, you can use my macro.

Maybe you are looking for