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
Similar Messages
-
HOw to create a text file in the given path and delete it after the use?
Hi all,
I am trying to create a text file at the given path and delete the created file after the use.
I am using following code.:
import java.io.*;
// write binary data as characters
public class RanIO {
public static void main(String f[])
// First illustrate append
String lineSep = "\n";
try {
File temp= new File("C:/Ash","cute.txt");
boolean ch=temp.createNewFile();
if(ch)
System.out.println("file created");
else
System.out.println("file Not created");
//writing to file
/* PrintWriter p = new PrintWriter(new BufferedWriter(new FileWriter("cute.txt",true)));
p.print("Emp NO");
p.close();*/
// Open fileWriter in append mode
FileWriter fos = new FileWriter(temp, true);
BufferedWriter bw = new BufferedWriter(fos);
PrintWriter pw = new PrintWriter(fos);
double d=550;
// lineSep = System.getProperty("line.separator");
pw.print("Hello");
//pw.print( lineSep );
pw.print( d );
pw.close();
boolean det=temp.delete();
if(det)
System.out.println("File deleted");
else
System.out.println("File not deleted");
} catch (IOException ioe)
System.out.println( "Append IO error:" + ioe );
My problem:
1)
I am not able to write to the file. I want to know, where i am going wrong.
It is giving error message like
"Canot resolve Symbol: temp,"
But, FileWriter Constructor should accept a File type parameter.
here temp is a file parameter.
If i am not using file=new file();
i can't delete the file after the use. i.e if i use
PrintWriter p = new PrintWriter(new BufferedWriter(new FileWriter("cute.txt",true)));
how can i delete cute.txt after the use?
2)
I am not able to write to the text file. file is created but, a blank file.
"Hello" is not written into the text file.
can anyone help me in this regard
Thanks in advance
AshviniThank you Ram,
But, i want to create a text file in Append mode.
for that i used
FileWriter fos = new FileWriter(temp,true); But, it is not accepting FileWriter constructor in
this format. if i use
FileWriter fos = new
FileWriter("c:/ash/cute.txt",true); it works fine. !!!!!Here's the javadoc
public FileWriter(File file,
boolean append)
throws IOExceptionConstructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning
Throws:
IOException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
Since:
1.4
Are you using jdk.13 or lower ?
>
ONe more doubt, Does flush method deletes a file?
if not, then i need to use
File temp=new File("c:/ash/cute.txt");
FileWriter fos = new FileWriter(temp,true); //which
is again a problem
if(temp.delete())
out.println("File is deleted");
}I don't know whether i am taking it wrong ! or
anything wrong with my coding ! but, after creating
and writing data into a text file. I must delete it
as it contains confidential informations.
Regards,
Thanks.'flush' writes to a file immediately. Else you should explicitly call 'flush' to write contents from buffer to underlying source.
javadoc again
PrintWriter
public PrintWriter(Writer out,
boolean autoFlush)Create a new PrintWriter.
Parameters:
out - A character-output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer
cheers,
ram.
Question; What do you gain by opening a file, writing to it and deleting it in the same program ? -
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. -
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 -
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 0170005486989873 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,
BuckyUse 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? -
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 Vadlamudi868591 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 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,
AndreaThis 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. -
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(); -
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 AlotGenrally 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,
MehulHi 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
Maybe you are looking for
-
Greying out multiple fileds in one shot?
Hello, I am developing a interactive form (visitor info form) with webdynpro ABAP. In the initial screen of my_webdynpro, there are couple of radio buttons, US, Europe, Asia. If user selects US radio button: I have to greyout & readOnly the below 4 i
-
Auto Saving of HCM interactive form in Background
Hi , We are using HCM Forms and Process to automate the processes where user fills the interactive form from EP and after that workflow will take care of approvals and finally data of the form is saved in the infotypes.Till now its working fine. But
-
Hi All I am doing a scenario from (Http-JDBC) I am using BPM in the scenario. What type bridge I should use in the BPM Thanks Jayaraman
-
Continously Clicking the Browser Off and On
Whenever i attempt to view a YouTube Video, the browser keeps acting like im clicking off of it and clicking onto it again. It keept repeating that until i closed the tab, then it went back to normal.
-
Hello to all, how can I debug a WD4A application. If I set an external breakpoint in SE80 the requested application dumps. Regards Christian