File writing
Hi,
Can anyone tell me, how can i write a text file which is located in my "webapps/log/log.txt" location? Two line sample code to get ouput stream will be very helpful.
Regards.
Jahid
Double post: http://forum.java.sun.com/thread.jspa?threadID=5177003&tstart=0
Similar Messages
-
Please someone, help me,
Why when I'm trying to reinstall my OS, Tiger 10.4, at 56% of the installation, at files writing, it keeps on shutting off?Does it feel extra hot on top?
Are you reinstalling because you had several problems? If so what were they?
"Try Disk Utility
1. Insert the Mac OS X Install disc, then restart the computer while holding the C key.
2. When your computer finishes starting up from the disc, choose Disk Utility from the Installer menu at top of the screen. (In Mac OS X 10.4 or later, you must select your language first.)
*Important: Do not click Continue in the first screen of the Installer. If you do, you must restart from the disc again to access Disk Utility.*
3. Click the First Aid tab.
4. Select your Mac OS X volume.
5. Click Repair Disk, (not Repair Permissions). Disk Utility checks and repairs the disk."
http://docs.info.apple.com/article.html?artnum=106214 -
I have to build a web application using servlet and jsp. The user should edit some
text file (maybe displaying the file fields in a HTML form).
I need some suggestions about implementing the synchronization on file writing (since different
users should try to save the same file simultaneously).
Do some standard pattern exist about this feature ?
I suppose to do that using a java bean whith application scope shared by the jsp pages. In this bean
I will implement all write methods using synchronized.
Any suggestions ?
Thanks in advance,
Mauro.well, if you have a single method which does the actual file writing, then you make that method synchronized and you'll have no problems. You can build up the data to write in some object at any time and pass that to that method.
However, that's still going to present problems when users actually modify the file at the same time. Why does every user have to share 1 file? -
Hi all,
I'm creating a simple app that gets form data and populates it to a file. I want to make sure that each instance (thread?) is able to write to the file and not throw an exception since the file may be currently open by another instance of the jsp. Now I did basic thread programming in C++ a long time ago, so I'm aware of thread waiting conceptually, but I'm not familiar with the java implementation. Can someone show me some basic syntax on how I would go in essentially putting a lock on the file writing portion of the code.
Thanx muchI disagree that you should override anything in Threa, especiially the sleep method.
What you should do is handle the file writing in a producer/consumer fashion. Have a single class that extends Runnable be the consumer. It handles all the file writing issues. You will run this in its own thread.
Your JSPs (or other threads) fill in a collection, or some other holder, which informs the consumer to write to the file.
As a brief example, this is a mini logger type of program. I use a class (LogCenter) to log data put in it from other sources (client1 and client2). For the sake of using newer API, I make use of the java.util.concurrent.BlockingQueue (and java.util.concurrent.LinkedBlockingQueue) to make a thread-safe collection and reporting system for text to come in and out of the logger.
Note, this is far from production. Just something I whipped up when playing with blocking queues a while ago...
package net.thelukes.steven.thread.test;
import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class LoggingCenter implements Runnable {
private PrintWriter output;
private BlockingQueue<String> toPrint;
public LoggingCenter() {
toPrint = new LinkedBlockingQueue<String>(10);
public void setOutput(PrintWriter pw) {
if (pw == null) {
if (output != null)
return; //do not replace output with null
else //pw is null and output is null
throw new IllegalArgumentException("Ouput PrintWriter must not be NULL");
else {
if (output != null) closeOutput(); //if output exists already, close it.
output = pw;
public void log(String text) {
boolean added = false;
while (!added)
try {
toPrint.put(text);
added=true;
} catch (InterruptedException ie) {
ie.printStackTrace();
try { Thread.sleep(300L); }
catch (InterruptedException ie2) { ie2.printStackTrace();}
public void run() {
try {
while (true) {
printLn(toPrint.take());
} catch (InterruptedException ie) {ie.printStackTrace();}
private void closeOutput() {
output.flush();
output.close();
private void printLn(String text) {
if (output == null)
throw new IllegalStateException
("The Output PrintWriter must be set before any output can occur.");
output.println(text);
output.flush();
package net.thelukes.steven.thread.test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class LoggingTest {
public static void main(String[] args) throws IOException {
PrintWriter output = new PrintWriter(
new FileWriter(new File("log.txt")));
//PrintWriter output = new PrintWriter(System.out, true);
final LoggingCenter logger = new LoggingCenter();
logger.setOutput(output);
Thread t = new Thread(logger);
t.start();
Thread client1 = new Thread(
new Runnable() {
public void run() {
while (true) {
logger.log("Client 1: "+System.currentTimeMillis());
try {
Thread.sleep(1250L);
} catch (InterruptedException e) {}
Thread client2 = new Thread(
new Runnable() {
public void run() {
while (true) {
logger.log("Client 2: "+System.currentTimeMillis());
try {
Thread.sleep(2500L);
} catch (InterruptedException e) {}
client1.start();
client2.start();
} -
File writing permissions??
is there any file writing permissions in jsp?
i can create folders with my code on my localhost Tomcat 5.5.
but now i have a webhost which has Tomcat 5.0...with my same jsp code i can see the content of my folders but cannot create any new folders under wwwroot or somewhere else on my webhost...
so i am thinking if it is related with permissions or something like that?please show me a way
thanks
Burakmy host admin responded;
Hi,
We can enable write permission, but this will put you in high security risk in tomcat shared hosting, as any other user also from his jsp/servlet script can write anything into your directory or delete file.
Now what you think?what i want to do is i have a photo album site...users can create their own folders and upload their photo albums...but this users' main folder must be somewhere in a protected area that users musnt directly link to this photos...like before wwwroot or after WEB-INF folder...where can it be?
please help me in this subject..need really help..
thanks -
Does UTL_FIL utility supports file writing in to remote Host ??
Hi,
I am checking the possibility with UTL_FIL utility whether supports file writing in to remote Host. My database is on different server from UNIX server but i want to make use of Oracle directory objects or UTL_FILES functions to be able to write files directly from Oracle to remote UNIX server.
Is this possible ?
Thanks
AnandUTL_FILE, and any other PL/SQL package running on the database server, can only access objects that the database server has access to. Unless the remote Unix server's file system is mounted from the Oracle server's file system, UTL_FILE would be unable to create a file there.
Now, there may well be alternateives. For example, you could generate the file locally and FTP the file to the remote Unix server, assuming the remote Unix server is running a FTP server.
Justin -
File Writing - Missing some files without any error
I am executing the following code:
String message = XMLHelper.getDocumentXML(_doc);
File outFile = getFile();
RandomAccessFile raf = new RandomAccessFile(outFile, "rw");
FileChannel channel = raf.getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(19600);
buf.clear();
buf.put(message.getBytes());
buf.flip();
channel.write(buf);
channel.close();
raf.close();
This code is in a loop and it must write a lot of files. I am trying with 426 but thje problem i have is that many times i do get 425 files insted of 426 or some other times i do get 425 files. No error or exception is thrown. Other times id do get my 426 files.
The problem increase when i process like 50000 files, the quantity it is supposed to treat.
Please can any body tell me what happen with the missing files? How can i detect what is happening?
Thank you very much to any one who can help me with this extrange errorHard to tell based on the info you supplied. How are you generating filenames? Are you accidently writing over an existing ouput file? Can you post more code, speciifcally the loop code around the code below?
-
Problem in creating New line in --File writing(Urgent)
Hi all
I am facing a tipical problem.
I am writing a Text file using FileWriter and i am using "\n" for writing a new line,
but when i open notepad all are falling on a single line with a special char
(if i open the text file in some other editor vie wis very fine)
C-0-1@C-1-0@ C-2-1
@ is where i am writing new line.
but this king of writing is not supported by my third party tool to which i am sending the text file
as parameter..
Kindly any one provide me a solution.
Byenewlines differ between windows and linux/unix. Windows' new line character is somthing like "\n\m" where linux uses "/n". So to keep your program platform independent I would suggest using System.getProperty("line.separator") so your code might look like:
String s = "C-0-1" + System.getProperty("line.separator") + "C-1-0" + System.getProperty("line.separator") + "C-2-1";
//then write the string to the filethis will give you the appropriate newline character for the platform your program runs on. -
Hello, I have a problem with writing a file. My code is very simple..it takes a line from one file, a line from a second file, combines them, and writes them into the third file. However, the program never gets past the point where it creates the output file. Any help is appreciated.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MergeFiles extends JApplet implements ActionListener
private final String filename = "mergedfiles.txt";
BufferedReader f1in, f2in;
FileOutputStream outputstream;
JTextField f1f = new JTextField("file1.txt", 20);
JTextField f2f = new JTextField("file2.txt", 20);
String F1text, F2text, F3text;
JLabel title = new JLabel("Merge files program! Press enter to merge!");
JButton merge = new JButton("MERGE! MERGE! MERGE!");
JLabel labelone = new JLabel("File one");
JLabel labeltwo = new JLabel("File two");
Container con = getContentPane();
JPanel pane = new JPanel();
GridBagConstraints c = new GridBagConstraints();
public void makedisplay()
Insets i = new Insets(10, 10, 10, 10);
pane.setLayout(new GridBagLayout());
pane.setBackground(Color.green);
con.setBackground(Color.green);
con.add(pane, BorderLayout.CENTER);
con.add(title, BorderLayout.NORTH);
c.weightx = 0;
c.insets = i;
c.gridy = 0;
c.gridx = 0;
pane.add(labelone, c);
c.gridx = 1;
pane.add(labeltwo, c);
c.gridx = 0;
c.gridy = 1;
c.ipadx = 50;
pane.add(f1f, c);
c.gridx = 1;
pane.add(f2f, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 3;
c.ipadx = 0;
pane.add(merge, c);
public void init()
makedisplay();
merge.addActionListener(this);
public void actionPerformed(ActionEvent e)
openfiles();
File f = new File("H://mergefiles//mergedfile.txt");
try {
title.setText("AAA");
BufferedWriter out = new BufferedWriter(new FileWriter(f));
F1text = f1in.readLine();
F2text = f2in.readLine();
title.setText("BBB");
F3text = "" + F1text + F2text;
out.write("" + F3text);
f1in.close();
f2in.close();
out.close();
catch (IOException ex)
public void openfiles()
try
BufferedReader f1in = new BufferedReader(new FileReader(f1f.getText()));
title.setText("file one opened");
catch (FileNotFoundException e)
title.setText("File one not found!");
try
BufferedReader f2in = new BufferedReader(new FileReader(f2f.getText()));
title.setText("File two opened");
catch (FileNotFoundException e)
title.setText("File two not found!");
}Nevermind, I've fixed the problem...for some reason you can't use the writer with an applet. I've written some new code that works:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MergeFiles2
static String F1L = "", F2L = "";
static File file1 = new File("H://mergefiles//file1.txt");
static File file2 = new File("H://mergefiles//file2.txt");
public static void main(String[] args) throws IOException
PrintWriter out = new PrintWriter(new FileWriter("file3.txt"));
BufferedReader f1in = new BufferedReader(new FileReader(file1));
BufferedReader f2in = new BufferedReader(new FileReader(file2));
while (F1L != null)
F1L = f1in.readLine();
if (F1L != null)
out.println(F1L);
while (F2L != null)
F2L = f2in.readLine();
if (F2L != null)
out.println(F2L);
out.close();
} -
Applet file writing without permission
Is it possible for an applet to write a text or html document to be displayed in a browser without needing to grant it permissions?
I experimented with writing a file and naming the file to the directory that the applet's in using getCodeBase(), but that didn't work. I've been looking into writing directly to a browser, but that's kind of ugly, and it looks like you have to play with system paths and what-not in order to talk to javascript, so I ruled that out. Any help is appreciated.
-
Hi,
I have a written a Java Program which Splits any File into two Parts. These parts can again later be rejoined to restore the Original File.
This is how Splitting Operation is performed
1. Read the SourceFile into Array of Bytes
2. Open two FileOutputStreams and Write these Bytes, half of it in each stream. This is Done using a Thread for Each stream, Obviously to save time.
3. Now i have two Files which contain Bytes for Original File.
Now in Restoring Operation:
1. Read the two Files(split using above technique) and store in Byte Arrays.
2. Open the FileOutputStream to a File and write the Above byte Arrays ONE BY ONE into this Stream.
Please note that i had to write Bytes from two byte arrays in the Order i had read it.
Which means to say that i first have to write From First Byte Array, wait for it to finish it and than write from Second Byte Array. I cannot start Threads for Writing Bcoz the Target File is Same. Also, i wouldn't know where to start writing the bytes from Second Byte Array in the target File since, the First Thread may still be performing the Write Operation from the First Byte Array
If i had been writing a C program, this would be fairly easy since i have File Pointers. I can use two programs and use fseek() operation to Know exactly where to start writing from second set of Byte Array.
Please give ur suggestion to above problem. How can i simulate File Pointer operations of C in Java.
I hope i am Clear in describing the Problem. If not, then please let me know......and Thnx for u Patiencetry not to cross post.
http://forum.java.sun.com/thread.jsp?forum=4&thread=165965&start=0&range=30#501577 -
File Writing Issue :-(
Hello Guys,
Im trying to write into a file from a InputStream..For which the code is as followspublic void saveFile(String filename,InputStream inpStr)
try{
InputStreamReader stream=new InputStreamReader(inpStr,"SJIS");
File tobSavedFile=new File(filename);
FileOutputStream fstr=new FileOutputStream(tobSavedFile);
while (true){
int d=stream.read();
if (d==-1) break;
else
fstr.write(d);
catch(Exception me){
me.printStackTrace();
}This code works fine when i pass a Text file as inputstream,But it doesnt work good when i pass a GIF or JPG or ZIP file in inputStream...
For example when i passed a file as GIF which was 1.45KB it resulted in creation of GIF file of just 1.34KB..
Why is this??can any one help me..
Thanks a lot for your patience.
Regds,
GokulDon't use an InputStreamReader around your InputStream, it's trying to do text conversion and not supposed to be used for binary data.
-
Hello All,
Below is the flat file output:
HEADER1
LINE ITEM1
LINE ITEM2
==
==
HEADER2
LINE ITEM3
LINE ITEM4
==
==
TRAILER
When PI is reading the above flat file below is xml structure generating:
<HEADER1>
<LINEITEM1>
<LINEITEM2>
==
<HEADER2>
<LINEITEM3>
<LINEITEM4>
==
<TRAILER>
Till now everything is working fine. In my message mapping I am performing some validations after that I am trying to write the same Input file in the same structure. But I am getting flat file in below format:
HEADER
HEADER
LINE ITEM1
LINEITEM2
LINEITEM3
==
===
I am expecting in same Input format i.e. as below:
HEADER1
LINE ITEM1
LINE ITEM2
==
==
HEADER2
LINE ITEM3
LINE ITEM4
==
==
TRAILER
How can I get the above structure?Hi,
you can convert the strucutre to flat file in File adapter using conversionType as "StructPlain2XML". And as you Lineitem are comming in variable sequence you need to use the parameter:
xml.recordsetStructureOrder - var
Regards,
Harish -
hai all
i am trying to write some data into file in JSP
my web structure is
/jsp
/jsp/others
my jsp file is in .jsp i want to create a file called Rajesh.txt in /jsp/others/Rajesh.txt
when i write
rintWriter fileObject = new PrintWriter(new FileWriter("./others/Rajesh.txt",false));
fileObject.write("Hello World");
its throwing .\others\Rajesh.txt (The system cannot find the path specified) Exception
please help me
Rajesherror once more for code
PrintWriter fileObject = new PrintWriter(new FileWriter(getServletContext().getRealPath("others/Rajesh.txt"),false));
C:\JavaWorld\Tomcat4.1\bin\..\webapps\finalmpc\others\Rajesh.txt (The system cannot find the path specified)
why ?? -
Plain file writing vs. Object writing
Hi,
I've a question about the use of object serialization when it comes to file io. Suppose I've written a binary tree datastructure, which is a pretty complex one. I've filled the tree with many object and now I want to be able to save the tree for later use. I could design some file format for the tree. But I could also use object serialization and write the whole tree object to file using the ObjectOutputStream. This makes it a lot easier.
I also could write a simple preferences object (a static class with static Strings, which define my preferences) to a file, without saving the preferences using some file format.
Now my question is: is object serialization meant for these types of things? Is this a good way of using it, or, for example, are the files going to be larger than necessary?
Thank you!
JeroenSerialization will give you a pretty compact file. Not neccesarily the smallest possible file, but you would need to spend some time and effort creating aformat that yields smaller files, and there's not much space to gain this way.
Serialization is fine when you never want to read the file with a program that's not written in java. Because reading a serialized file using a non-java program would mean implementing the code to parse and understand the encdings for the java object format and the java primitive types.
Serialization pretty much prevents you from doing meaningsfull inspection of your data using less, grep or a text editor. If you want to be able to do this, then use a custom format that's built for readibily with such tools. It can still be pretty compact.
Maybe you are looking for
-
I updatedmy PC from Windows 7 to Windows 8. I can no longer sync my Contacts and Calendar between my iPhone and my computer.
-
How to set password policy for apps users
Hi All, Can anyone please help me. I am working on apps 11i. How to set password policy for users Thanks
-
In my third-party web application of Office 365, I want to have access to the contacts, events and emails of all the users from the organizations who installed my app. The thing is I don't want that all these users have to grant me access, I just wan
-
Hey everyone im making a program that involves making a url connection. I create the URL object and then the URLConnection object, but when i go to find out hte contentlength, it always returns negative one. i think that the problem is that the url c
-
I recently read that netflix' watch instantly option can work on macs. I used a link for the silverlight "opt in" option. The website said "congragulations the new media player is enabled." When I try to watch a movie though, it says my OS is not com