Writing in a text file

Hi ,
Can you send the syntax of :
1/ How can i open a text file
2/ How can i create a text file
3/ How can i write in a text file
4/ How can i delete a text file
Please advise ,
Thank you .

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

Similar Messages

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

  • Writing records to text file

    Hi. I have a query that retrieves data in a table. however when writing into text file, I have some troubles aligning the records.
    In below example, how would align the data against its header?? thanks!
    As you see my data below is messed up =(
    Ex.
    Reference No. Name Phone No.
    012-066-121127-00227 MARIE LIM JOSEPH     2921786     
    013-318-130222-04992 NANCY SMITH     0170005486

    989873 wrote:
    Hi. I have a query that retrieves data in a table. however when writing into text file, I have some troubles aligning the records.
    In below example, how would align the data against its header?? thanks!
    As you see my data below is messed up =(
    Ex.
    Reference No. Name Phone No.
    012-066-121127-00227 MARIE LIM JOSEPH     2921786     
    013-318-130222-04992 NANCY SMITH     0170005486you need to fix your code;
    consider using LPAD or RPAD as appropriate

  • Writing from a text file into a table

    Hi,
    I have a problem with dearchiving the data from the txt file to the respective table.
    The table name is dynamic & I get the required columns from all_tab_columns.
    I use UTL_FILE.GET_LINE() to get the data one line at a time and INSTR() & SUBSTR() to break them into the respective columns.
    My dynamic insert contains a set of bind variables equal to the no. of columns of the table.
    The statement gets constructed correctly but I tried to use execute_immediate , i realised that i cannot construct the USING clause for it & hence I switced to DBMS_SQL.
    The DBMS_SQL.BIND_VARIABLE() binds all of the bind variables to a table of varchar2. I've taken care to convert the date & the number variables while binding.
    When i do DBMS_SQL.EXECUTE() I get the error,
    ORA-01008 Not all variables bound .
    I don't know the reason since the no. of bind variables & the no. of table variables are the same & the value in the table looks fine too!
    Could this be a date issue ??? am using the default format DD-MON-YY both to write to the text file and to read from it.
    Any help would be appreciated.
    thx
    kalpana
    Part of the code :
    Begin
    destination_file := upper(p_table_name)||'_ARCH'||to_char
    (p_process_date,'yyyymmdd')||'.dat';
    dbms_output.put_line(destination_file);
    file_id := UTL_FILE.FOPEN(file_path, destination_file,'r');
    -- Get the number of columns in the table to be archived
    select count(column_name)
    into col_ctr
    from all_tab_columns
    where table_name = upper(p_table_name)
    order by column_name;
    sql_stmt1 := 'Insert into '||p_table_name||'(';
    sql_stmt2 := ' values(';
    For col_rec in column_cur loop
    if col_ctr = column_cur%rowcount then -- last column in
    the select statement
    sql_stmt1 := sql_stmt1 || col_rec.column_name;
    sql_stmt2 := sql_stmt2||':b'||column_cur%rowcount;
    else
    sql_stmt1 := sql_stmt1 || col_rec.column_name ||',';
    sql_stmt2 := sql_stmt2||':b'||column_currowcount||',';
    end if;
    type_rec(column_cur%rowcount) := col_rec.data_type;
    end loop;
    sql_stmt1 := sql_stmt1||')';
    sql_stmt2 := sql_stmt2||')';
    sql_stmt := sql_stmt1||sql_stmt2;
    loop
    Begin
    UTL_FILE.GET_LINE(file_id,v_column_value);
    For i in 1..col_ctr loop
    v_next_position := INSTR(v_column_value,';',1,i);
    if i = 1 then
    v_rec(i) := SUBSTR(v_column_value, v_prev_position, v_next_position - 1);
    elsif i = col_ctr then -- last but one column
    v_rec(i) := SUBSTR(v_column_value, v_prev_position);
    else
    v_rec(i) := SUBSTR(v_column_value, v_prev_position, (v_next_position - v_prev_position));
    end if;
    v_prev_position := v_next_position + 1;
    end loop;
    v_cursor := DBMS_SQL.OPEN_CURSOR;
    DBMS_SQL.PARSE(v_cursor, sql_stmt, dbms_sql.native);
    For i in 1..col_ctr loop
    if type_rec(i) = 'DATE' then
    DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||i, to_date(v_rec(i),'DD-MON-YY'));
    elsif type_rec(i) = 'NUMBER' then
    DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||i, to_number(v_rec(i)));
    end if;
    end loop;
    -- Insert the row into the history table
    -- execute immediate sql_stmt USING value(v_rec);
    v_dummy := DBMS_SQL.EXECUTE(v_cursor);
    if SQL%NOTFOUND then
    dbms_output.put_line('CPN_HISTORY_ARCHIVE_PKG.DEARCHIVE_DATA : No records to insert');
    end if;
    Exception -- for UTL_FILE.GET_LINE
    when NO_DATA_FOUND then
    DBMS_SQL.CLOSE_CURSOR(v_cursor);
    UTL_FILE.FCLOSE(file_id);
    exit;
    End;
    end loop; -- end of loop for UTL_FILE.GET_LINE
    DBMS_SQL.CLOSE_CURSOR(v_cursor);
    UTL_FILE.FCLOSE(file_id);

    your program is currect except u r not building bind variables for varchar2 columns
    declare
    type tab133 is table of varchar2(4000) index by binary_integer;
    file_id utl_file.file_type;
    sql_stmt1 varchar2(1000);
    sql_stmt2 varchar2(1000);
    v_column_value varchar2(1000);
    sql_stmt varchar2(2000);
    col_ctr number:=0;
    p_table_name varchar2(30):='emp1';
    cursor column_cur is select column_name,data_type from user_tab_columns
    where table_name=upper(p_table_name);
    mainstr      VARCHAR2(40)          :=      '';
    splitstr      VARCHAR2(30)          :=     '';
    l_count      NUMBER(20)          :=     1;
    itr_count      NUMBER(20)          :=     0;
    processed      BOOLEAN               :=     FALSE;
    v_rec tab133;
    type_rec tab133;
    v_cursor integer;
    column_currowcount number;
    v_dummy number:=0;
    Begin
    --dbms_output.put_line(destination_file);
    file_id := UTL_FILE.FOPEN('c:\suresh', 'emp.txt','r');
    -- Get the number of columns in the table to be archived
    select count(column_name)
    into col_ctr
    from user_tab_columns
    where table_name = upper(p_table_name)
    order by column_name;
    sql_stmt1 := 'Insert into '||p_table_name||'(';
    sql_stmt2 := ' values(';
    For col_rec in column_cur loop
    if col_ctr = column_cur%rowcount then
    sql_stmt1 := sql_stmt1 || col_rec.column_name;
    sql_stmt2 := sql_stmt2||':b'||column_cur%rowcount;
    else
    sql_stmt1 := sql_stmt1 || col_rec.column_name ||',';
    sql_stmt2 := sql_stmt2||':b'||column_cur%rowcount||',';
    end if;
    type_rec(column_cur%rowcount) := col_rec.data_type;
    end loop;
    sql_stmt1 := sql_stmt1||')';
    sql_stmt2 := sql_stmt2||')';
    sql_stmt := sql_stmt1||sql_stmt2;
    dbms_output.put_line(sql_stmt);
    loop
    Begin
    UTL_FILE.GET_LINE(file_id,v_column_value);
         itr_count      :=     0;
         l_count :=1;
         processed     :=     FALSE;
    mainstr:=v_column_value;
         LOOP
              itr_count     :=      itr_count+1;
              IF instr(mainstr,',',1,itr_count)>0 THEN
                   splitstr      :=     SUBSTR(mainstr,l_count,(INSTR(mainstr,',',1,itr_count)-l_count));
                   l_count          :=     INSTR(mainstr,',',1,itr_count)+1;
              ELSE
                   splitstr      :=      SUBSTR(mainstr,l_count,LENGTH(mainstr)+1-l_count);
                   processed     :=     TRUE;
              END IF;
              v_rec(itr_count):=splitstr;
              IF processed THEN
                   EXIT ;
              END IF;
         END LOOP;
    v_cursor := DBMS_SQL.OPEN_CURSOR;
    --dbms_output.put_line(col_ctr);
    DBMS_SQL.PARSE(v_cursor, sql_stmt, dbms_sql.native);
    For i in 1..col_ctr loop
    if type_rec(i) = 'DATE' then
    DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||to_char(i), to_date(v_rec(i),'DD/mm/yyyy'));
    elsif type_rec(i) = 'NUMBER' then
    DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||to_char(i), to_number(v_rec(i)));
    elsif type_rec(i) = 'VARCHAR2' then
    DBMS_SQL.BIND_VARIABLE(v_cursor,':b'||to_char(i), v_rec(i));
    end if;
    end loop;
    v_dummy := DBMS_SQL.EXECUTE(v_cursor);
    if SQL%NOTFOUND then
    dbms_output.put_line('CPN_HISTORY_ARCHIVE_PKG.DEARCHIVE_DATA : No records to insert');
    end if;
    DBMS_SQL.CLOSE_CURSOR(v_cursor);
    Exception
    when NO_DATA_FOUND then
    UTL_FILE.FCLOSE(file_id);
    exit;
    End;
    end loop;
    UTL_FILE.FCLOSE(file_id);
    EXCEPTION
    when others then
    dbms_output.put_line(sqlerrm);
         UTL_FILE.FCLOSE(file_id);
    END;
    TEST:
    SQL> DESC EMP1
    Name Null? Type
    ENAME VARCHAR2(15)
    SUBJ VARCHAR2(15)
    SDATE DATE
    DATA FILE:
    AABC,oracle,08/08/2001
    xyz,social,12/12/2001
    SQL> select * from emp1;
    ENAME SUBJ SDATE
    AABC oracle 08/08/2001 00:00:00
    xyz social 12/12/2001 00:00:00

  • Reading and Writing to a Text File

    Hello all,
    I was wondering if it is possible to write from forms to a text file and if possible what is the best way to do it.
    Thanks,
    Bucky

    Use the TEXT_IO built-in functionality in forms or from the database utl_file. TEXT_IO seems to be more flexible because you can read and write to any server/directory you have access to whereas UTL_FILE is limited to the server where the database is located. Hope this helps.
    Mike

  • Reading and writing to a text file from an Applet

    I'm a novice java programming with very little formal programming training. I've pieced together enough knowledge to do what I've wanted to do so far...
    However, I've been unable to figure out how to read and write to a text file from an Applet (I can do it from a normal java program just fine). Here is a simple example of what I'd like to do (you can also look at it on my website: www.stat.colostate.edu/~leach/test02/test02.html). I know that there is some problem with permission/security but I'm not smart enough to understand what the error messages are telling or understand the few books I have. If anyone can tell me how to get this applet to work, or direct me to some referrences that would help me out I'd really appreciate it.
    Thanks,
    Andy
    import java.applet.Applet;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    public class test02 extends Applet {
    public Button B_go;
    public GridBagConstraints c;
    public void init() {
    this.setLayout(new GridBagLayout());
    c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    B_go = new Button("GO");
    c.gridx=1; c.gridy=0; c.gridwidth=1; c.gridheight=1;
    c.weightx = c.weighty = 0.0;
    B_go.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    print_stuff();
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    this.add(B_go,c);
    public static void print_stuff() {
    try{
    File f = new File("test02.txt");
    PrintWriter out = new PrintWriter(new FileWriter(f));
    out.print("This is test02.txt");
    out.close();
    }catch(IOException e){**/}
    }

    I have almost the exact same problem, and I am in the same situation as you are with respects to the language.
    I am simply trying to create a file and output some garbage to it but my applet always spits back a security violation. I've tried eliminating the restrictions on the applet runner I use but I still get the error.
    My method:
    debug = new Label() ;
    debug.setLocation( 20, 20 ) ;
    debug.setSize( 500, 15 ) ;
    add( debug ) ;
    // output
    try
         OutputStream file = new FileOutputStream( new File( "" + getCodeBase() + "output.txt" ) ) ;
         byte[] buffer = { 1, 2, 3, 4, 5 } ;
         file.write( buffer ) ;
         file.close() ;
    } catch( Exception e )
         debug.setText( e.toString() ) ;
         Can anyone tell why this isnt working?

  • Reading and Writing from a text file at the same time

    I know who to use the Scanner and PrintWriter to read from and write to a .txt file. But these are limited. How can I read and write at the same time? Such as open a file and change every third character or change every second word to something else and then write it back. I found this [http://java.sun.com/docs/books/tutorial/essential/io/|http://java.sun.com/docs/books/tutorial/essential/io/] but its a little over my head. Is this the only way to do it?

    wrote:
    You are using buffered reads and writes I would assume, right? Also, how do you think most programs handle this sort of thing? I don't believe I'm using buffering.
    My code looks something like this
    //...necessary imports
    //then
    Scanner inFile = new Scanner (new file("filename1.txt"));
    PrintWriter outFile = new PrintWriter ("filename2.txt");
    //then stuff like
    int x = inFile.hasNextInt();
    outFile.println(x);
    camickr wrote:If you are changing the data "in place", that is none of the data in the file is shifted, then you can use a RandomAccessFile.
    Otherwise, you've been given the answer above.What is RandomAccessFile? Is it what I have a link to? Basically what I do is I write a bunch of numbers to a txt file and then change the numbers I don't need anymore to 0. So say I had 0 1 2 3 4 5 6 7 etc. I would like to to open the txt file and change every second one to 0 so then I'd have only odd numbers and 0s.
    I looked at the documentation for RandomAccessFile and it seems like it might be what I need.
    Thankyou both for your help so far. I took a java course in high school and they only taught me one way to get data from text files and that is what I just showed you. So maybe this questions are really stupid. lol
    Edited by: qw3n on Jun 13, 2009 7:46 PM

  • Why this error in writing string to text file using utl_file?

    HI Friends,
    Iam trying to write procedure to add one line of text in text file using UTIL package. But getting error.
    create or replace procedure Add_To_File() is
    OutFile utl_file.file_type;
    l_err_code NUMBER(10);
    l_err_msg VARCHAR2(2000);
    vNewLine VARCHAR2(4000);
    vdir varchar2(200):='UTIL_DIR';
    begin
    OutFile:=utl_file.fopen(vdir,'out.txt','w','32000');
    vNewLine:='Loading is successfull';
    utl_file.put_line(OutFile,vNewLine);
    EXCEPTION
    WHEN OTHERS THEN
    l_err_code := SQLCODE;
    l_err_msg := SUBSTR(SQLERRM,1,128);
    Dbms_output.put_line(l_err_code || l_err_msg);
    end;
    when i execute above procedure iam getting this error.
    LINE/COL ERROR
    1/23 PLS-00103: Encountered the symbol ")" when expecting one of the
    following:
    <an identifier> <a double-quoted delimited-identifier>
    current delete exists prior
    Please suggest me where iam wrong.
    Thanks,
    Venkat Vadlamudi

    868591 wrote:
    HI Friends,
    Iam trying to write procedure to add one line of text in text file using UTIL package. But getting error.
    create or replace procedure Add_To_File() is
    OutFile utl_file.file_type;
    l_err_code NUMBER(10);
    l_err_msg VARCHAR2(2000);
    vNewLine VARCHAR2(4000);
    vdir varchar2(200):='UTIL_DIR';
    begin
    OutFile:=utl_file.fopen(vdir,'out.txt','w','32000');
    vNewLine:='Loading is successfull';
    utl_file.put_line(OutFile,vNewLine);
    EXCEPTION
    WHEN OTHERS THEN
    l_err_code := SQLCODE;
    l_err_msg := SUBSTR(SQLERRM,1,128);
    Dbms_output.put_line(l_err_code || l_err_msg);
    end;
    when i execute above procedure iam getting this error.
    LINE/COL ERROR
    1/23 PLS-00103: Encountered the symbol ")" when expecting one of the
    following:
    <an identifier> <a double-quoted delimited-identifier>
    current delete exists prior
    Please suggest me where iam wrong.
    Thanks,
    Venkat Vadlamudibelow works for me
      1  CREATE OR replace PROCEDURE Add_to_file
      2  IS
      3    outfile       utl_file.file_type;
      4    l_err_code NUMBER(10);
      5    l_err_msg  VARCHAR2(2000);
      6    vnewline   VARCHAR2(4000);
      7    vdir       VARCHAR2(200) := 'UTIL_DIR';
      8  BEGIN
      9    outfile := utl_file.Fopen(vdir, 'out.txt', 'w', '32000');
    10    vnewline := 'Loading is successfull';
    11    utl_file.Put_line(outfile, vnewline);
    12  EXCEPTION
    13    WHEN OTHERS THEN
    14            l_err_code := SQLCODE;
    15            l_err_msg := Substr(sqlerrm, 1, 128);
    16            dbms_output.Put_line(l_err_code
    17                           || l_err_msg);
    18* END;
    SQL> /
    Procedure created.

  • Writing in a text file at a given place

    Hello !
    Hier is my problem : i've got a text loaded from a text file, displayed into a jEditorPane. I select a part of this text, and I'd like to write a String text at the beginning (and end) of this selection, in the original text file.
    I can get the position of beginning and end of my selection with jEditorPane.getSelectionStart(), but how can I write any String in a .txt file at this given place ?
    Bastet

    Hi again
    if you try to insert html tag in your JEditorPane, you should use the defaults action that HTMLEditorKit & JEditorPane have, for example bold action, italic, underline, color font etc...
    but if you insist to insert tag manually you should use this
    JEditorPane jep;
    btn.actionPerformed(
    new ActionListener (){
    public void actionPerformed(ActionEvent e){
    String st = jep.getSelectedText();
    int pos = jep.getSelectionStart();
    jep.replaceSelection("");
    (jep.getDocument()).insertString(pos,"<b>"+st+"</b>",null);
    this maybe could help you...
    by the way (without offending) that so followed you read the API of JAVA? you could find a lot of your answer
    Greetings
    e_santiago

  • Writing or modifying text files in java

    Dear all,
    I have the next text file:
    goods: 5
    bids: 4
    % num, price, good, good, ..., good, #
    0 2075 1 4 #
    1 3000 1 2 3 4 #
    2 520 3 #
    3 3000 2 3 4 #
    I have to modify or create the file above, using output data from one java program. For example, The output of my java program in the next execution is:
    goods: 8
    and price (0) changes from 2075 to 2078.
    so, using this output data my java program should write (create or modify) the next text file with the changes:
    goods: 8
    bids: 4
    % num, price, good, good, ..., good, #
    0 2078 1 4 #
    1 3000 1 2 3 4 #
    2 520 3 #
    3 3000 2 3 4 #
    I have tried using: output.write( objetc );
    but it doesn't work as I need :( .
    Somebody can help me or give me some idea?
    Thanks,
    Andrea

    This is the code:
    File testFile = new File("D:\\result1.txt");
    setContents(testFile, " bla bla bla (few characters) ");
    static public void setContents(File aFile, String aContents)
    throws FileNotFoundException, IOException {
    try {
    //use buffering
    output = new BufferedWriter( new FileWriter(aFile) );
    output.write( aContents );
    finally {
    //flush and close both "output" and its underlying FileWriter
    if (output != null) output.close();
    I mean, this code dont work because it let me write few characters only. I need to write the whole file:
    goods: 8
    bids: 4
    % num, price, good, good, ..., good, #
    0 2078 1 4 #
    1 3000 1 2 3 4 #
    2 520 3 #
    3 3000 2 3 4 #
    with the special characters as (#).
    Sorry, if it post is not clear.
    Thanks.

  • Writing to A text file that is located on an online directory.

    I have an application that several users will be using. The program outputs a string when a submit button is clicked. I have a txt file called Data.txt which resides on a web directory with the following url. http://nath5.hostrator.com/............/Data.txt I need some way to have the string that the program outputs to be appended to the txt file. I have talked to my computer science teacher and he wasn't really sure how to do this in java. I am still a beginner, so any help anyone can offer would be great.
    Thanks Alot

    Genrally speaking you can't "write" to any random HTTP URL. HTTP is primarily a read-only protocol (it has PUT and POST, but those are not widely used for directly writing to URLs).
    You could use WebDAV (which is an extension of HTTP), if the server is set up to allow it.
    Another common approach is to use ftp to access the files directly ('though you'd obviously need a ftp:// URL instead of a HTTP:// one).

  • Writing data in text file..

    1. check the file name in D:\\temp\\test.txt
    2. if it exists, then open file. if there is data, then read data. after the last record, it writes new data.
    3. if it does not exist, create text.txt file and write data into text.txt file.
    so far, I have a code..
    import java.io.*;
    import java.util.*;
    public class Main {
    public static void main(String[] args) {
    String filename="test";
    String format = "%1$-9s%2$-3s%3$-30s%4$-30s%5$-30s\n";
    String arraydata[] = { "John", "F.", "Kennedy", " ", "t", "John2", "F2.", "Kennedy2", " ", "t2"};
    String cnt_id ="2";
    int cnt_orderid = Integer.valueOf(cnt_id);
    try
    PrintStream ps = new PrintStream(new FileOutputStream("D:\\temp\\"+filename+".txt"));
    for (int i=1; i<cnt_orderid; i++)
    ps.println(String.format(format, (Object[])arraydata)); // write in test.txt file
    ps.close();
    catch (Exception e)
    System.out.println(e);
    my question is..
    1. how to check the file exists or not
    2. how to write the data in the new line after the last data in the file.

    1. Use a File object.
    File file = new File("someFile.txt");
    if (file.exists()) { ... }2. Consider using FileWriter; the constructor allows you to append to the end of the file:
    FileWriter fileWriter = new FileWriter(file, true);Michael

  • Writing data in text file in KM

    Hi Experts,
    I am trying to write content in KM. my query is
    1) I tried with FileManagement, But it doesnn't work in KM. Why?? working well with file saved on server.
    2) I tried following code. But there in no exception,error and no result...
    try{
         String upstr="some data";
         IUser user =WPUMFactory.getUserFactory().getEP5User(req.getUser());
         ByteArrayInputStream data = new ByteArrayInputStream(upstr.getBytes());
         Content content = new Content(data,"text,plain",data.available()); //test
         ResourceContext ctxt = new ResourceContext(user);
         RID rid =RID.getRID("/documents/test.txt");
            ResourceFactory.getInstance().getResource(rid, ctxt).updateContent(content);
    }catch(Exception e){}
    Can you help please??
    Thanks in advance.
    Regards,
    Mehul

    Hi Mehul,
    -->I tried with FileManagement, But it doesnn't work in KM. Why?? working well with file saved on server.
    It is unclear what type of Repository you are using/having (FSDB/Webdav) and what you are trying to do!
    http://help.sap.com/saphelp_nw2004s/helpdata/en/62/468698a8e611d5993600508b6b8b11/frameset.htm
    --> I tried following code. But there in no exception,error and no result
    Use the below code to get things working
    public static IResource getOrCreateResource(String name, IResourceContext resourceContext)
            throws ResourceException {
            if (name != null) {
                name = name.trim();
            // Check that no part of the name has leading or trailing spaces / underscores
            RID collectionRID = RID.getRID(name);
              IResource collection = null;
              if (!ResourceFactory.getInstance().checkExistence(collectionRID, resourceContext)) {
    //In this method, passing true will create new Resource if not exists
                   collection = (IResource) ResourceFactory.getInstance().getResource(collectionRID, resourceContext, true);
              }else{
                   collection = (IResource) ResourceFactory.getInstance().getResource(collectionRID, resourceContext, false);
      return collection;
    IResource resource = getOrCreateResource(String name, IResourceContext resourceContext)
    String dataString = new String(content);
    ByteArrayInputStream dataStream = new ByteArrayInputStream(dataString.getBytes());
    IContent newContent = new Content( dataStream, text/plain, dataStream.available() );
    resource.updateContent(newContent);
    Also check this:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/5d0ab890-0201-0010-849d-98d70bd1d5f0
    Greetings,
    Praveen Gudapati
    p.s. Points are always welcome for helpful answers

  • Delimited output problem at the time of writing in to text file

    Hi ,
    I am using matrix stayle design for my reports when i am generating reports in delimited format i am getting Delimited output problem(DR.Watson ERROR) at the time of writing in to textfile.

    Hi,
    Try with new desformat delimiteddata which is available with Report 6i patch 11.
    Thanks
    Oracle Reports Team

  • Need Help: UTL_FILE Reading and Writing to Text File

    Hello I am using version 11gR2 using the UTL_FILE function to read from a text file then write the lines where it begins with word 'foo' and end my writing to the text file where the line with the word 'ZEN' is found. Now, I have several lines that begin with 'foo' and 'ZEN' Which make for one full paragraph, and in this paragraph there's a line that begins with 'DE4.2'. Therefore,
    I need to write all paragraphs that include the line 'DE4.2' in their beginning and ending lines 'foo' and 'ZEN'
    FOR EXAMPLE:
    FOO/234E53LLID
    THIS IS MY SECOND LINE
    THIS IS MY THIRD LINE
    DE4.2 THIS IS MY FOURTH LINE
    THIS IS MY FIFTH LINE
    ZEN/DING3434343
    FOO/234E53LLID
    THIS IS MY SECOND LINE
    THIS IS MY THIRD LINE
    THIS IS MY FIFTH LINE
    ZEN/DING3434343
    I am only interested in writing the first paragraph tha includes line DE4.2 in one of ther lines Not the Second paragraph that does not include the 'DE4.2'
    Here's my code thus far:
    CREATE OR REPLACE PROCEDURE my_app2 IS
    infile utl_file.file_type;
    outfile utl_file.file_type;
    buffer VARCHAR2(30000);
    b_paragraph_started BOOLEAN := FALSE; -- flag to indicate that required paragraph is started
    BEGIN
    -- open a file to read
    infile := utl_file.fopen('TEST_DIR', 'mytst.txt', 'r');
    -- open a file to write
    outfile := utl_file.fopen('TEST_DIR', 'out.txt', 'w');
    -- check file is opened
    IF utl_file.is_open(infile)
    THEN
    -- loop lines in the file
    LOOP
    BEGIN
    utl_file.get_line(infile, buffer);
         --BEGINPOINT APPLICATION
    IF buffer LIKE 'foo%' THEN
              b_paragraph_started := TRUE;          
         END IF;
         --LOOK FOR GRADS APPS
              IF b_paragraph_started AND buffer LIKE '%DE4%' THEN
              utl_file.put_line(outfile,buffer, FALSE);
    END IF;
         --ENDPOINT APPLICATION      
              IF buffer LIKE 'ZEN%' THEN
         b_paragraph_started := FALSE;
              END IF;
    utl_file.fflush(outfile);
    EXCEPTION
    WHEN no_data_found THEN
    EXIT;
    END;
    END LOOP;
    END IF;
    utl_file.fclose(infile);
    utl_file.fclose(outfile);
    EXCEPTION
    WHEN OTHERS THEN
    raise_application_error(-20099, 'Unknown UTL_FILE Error');
    END my_app2;
    When I run this code I only get one line: DE4.2 I AM MISSING THE ENTIRE PARAGRAPH
    PLEASE ADVISE...

    Hi,
    Look at where you're calling utl_file.put_line. The only time you're writing anything is immediately after you find the the key word 'DE4', and then you're writing just that line.
    You need to store the entire paragraph, and when you reach the end of the paragraph, write the whole thing only if you found the key word, like this:
    CREATE OR REPLACE PROCEDURE my_app2 IS
        TYPE  line_collection  
        IS       TABLE OF VARCHAR2 (30000)
               INDEX BY BINARY_INTEGER;
        infile               utl_file.file_type;
        outfile                      utl_file.file_type;
        input_paragraph          line_collection;
        input_paragraph_cnt          PLS_INTEGER     := 0;          -- Number of lines stored in input_paragraph
        b_paragraph_started      BOOLEAN      := FALSE;     -- flag to indicate that required paragraph is started
        found_key_word          BOOLEAN          := FALSE;     -- Does this paragraph contain the magic word?
    BEGIN
        -- open a file to read
        infile := utl_file.fopen('TEST_DIR', 'mytst.txt', 'r');
        -- open a file to write
        outfile := utl_file.fopen('TEST_DIR', 'out.txt', 'w');
        -- check file is opened
        IF utl_file.is_open(infile)
        THEN
         -- loop lines in the file
         LOOP
             BEGIN
              input_paragraph_cnt := input_paragraph_cnt + 1;
                 utl_file.get_line (infile, input_paragraph (input_paragraph_cnt));
              --BEGINPOINT APPLICATION
              IF LOWER (input_paragraph (input_paragraph_cnt)) LIKE 'foo%' THEN
                  b_paragraph_started := TRUE;
              END IF;
              --LOOK FOR GRADS APPS
              IF b_paragraph_started
              THEN
                  IF  input_paragraph (input_paragraph_cnt) LIKE '%DE4%'
                  THEN
                   found_key_word := TRUE;
                  END IF;
                  --ENDPOINT APPLICATION
                  IF input_paragraph (input_paragraph_cnt) LIKE 'ZEN%' THEN
                      b_paragraph_started := FALSE;
                   IF  found_key_word
                   THEN
                       FOR j IN 1 .. input_paragraph_cnt
                       LOOP
                           utl_file.put_line (outfile, input_paragraph (j), FALSE);
                       END LOOP;
                   END IF;
                   found_key_word := FALSE;
                   input_paragraph_cnt := 0;
                  END IF;
              ELSE     -- paragraph is not started
                  input_paragraph_cnt := 0;
              END IF;
              EXCEPTION
                  WHEN no_data_found THEN
                   EXIT;
              END;
          END LOOP;
        END IF;
        utl_file.fclose (infile);
        utl_file.fclose (outfile);
    --EXCEPTION
    --    WHEN OTHERS THEN
    --        raise_application_error(-20099, 'Unknown UTL_FILE Error');
    END my_app2;
    SHOW ERRORSIf you don't have an EXCEPTION section, the default error handling will print an error message, spcifying exactly what the error was, and which line of your code caused the error. By using your own EXCEPTION section, you're hiding all that information. I admit, the error messages aren't always as informative as we'd like, but they're never less informative than "Unknown UTL_FILE Error'. Don't use your own EXCEPTION handling unless you can improve on the default.
    Remember that anything inside quotes is case-sensitive. If your file contains upper-case 'FOO', then it won't be "LIKE 'foo%' ".
    Edited by: Frank Kulash on Dec 7, 2011 1:35 PM
    You may have noticed that this site normally doesn't display multiple spaces in a row.
    Whenever you post formatted text (such as your code) on this site, type these 6 characters:
    \{code}
    (small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.

Maybe you are looking for

  • Suggestion for a new feature

    There are some members of this community (Templeton Peck, for example) who spend a considerable amount of time scouring the forum for off-topic posts and offering guidance as to more appropriate venues to post questions and find information, usually

  • HP Scanjet G3010 driver for Windows 8.1

    Where can I find the driver of HP Scanjet G3010 for Windows 8.1 ?

  • Macbook Pro wakes up from sleep when express card inserted

    Hi, my macbook pro (no unibody, 10.5.7) wakes up from sleep when I have my express card 34 (Hama 16GB) inserted. Is there any trick to disable wake up when a drive is inserted? I tried to eject the disk before going to sleep with a shell script but i

  • Release Management fails to locate log file

    Hi, I'm using Visual Studio Release Management to deploy MSI packages. When I try to "View Log" I get the following error: There was an error while reading the log: Could not find file 'C:\Users\zzzzzz\AppData\Local\Temp\RM\T\RM\xxxxxx\20150305113557

  • .psd file reducing size when sending file to web guy who is using PC (1020x750 changing to 640x471)

    I have created a layered .psd file for a client of mine for his website who is dealing with a web guy in India to programme it. The guy in India is using a PC. The file when I send it out is sized 1020pixels x 750pixels, at 72dpi. When the web guy op