Problem with FileWriter class

JAVA

    Sponsored Links

    Next

  • 1. Java through (NTLM) proxy
    Hi all, I need urgent help on these (questions are numbered below): I know that I can set proxyhost and proxyport for the java application to work through a normal proxy server. But (at least) on corporate networks there are authentication schemes on proxys. I am using URLConnection with SSL encryption to encapsulate java objects that I transfer from our server to the (Java app) client that resides inside corporate network. I am aware of HTTPClient that claims to deal with the NTLM proxy, but how? Asking user for Windows l/p/d?!? I have found no examples nor tutorials that deal with this.. I have been searching web really for a while now and have found out that NTLM proxy authentication is Microsoft's authentication scheme that has no public specification!?! Is it really true that Java is not capable of dealing with corporate networks (or corporate proxies)? Do I really need to go to the JSP ect. road on this one? 1. Is it possible to get proxy settings somehow from the client computer other than asking them from the user? 2. Is it possible to use java application client to access server through NTLM proxy server? How? Example would REALLY be appriciated! 3. Is it possible to get somehow Windows credentials other than asking user (I guess that HTTPClient needs these)? Best Regards, Mika
  • 2. how can I get the text file's encode?
    I use the following codes to check what encode the file is ------- FileReader in=new FileReader("E:/aa.txt"); System.out.println(in.getEncoding()); ------- but it always print "GBK" when I point to different files whick I know they are ANSI , UNICODE and UTF my system is XP, and I make these different encode files by windows's note.exe how can I get the file's encode in java? and can I write a file with special encode I want? Thank you very much in advance.
  • 3. Some questions about the IO package
    I have learnt the java.IO these days but it puzzle me so much because it has too much classes to learn, such as InputStream,OutputStream,Writer,Reader and their numbers of subclasses. it take me so much time to learn and I can't get the point of the java.IO my question is: 1,Where do you use the java.IO,I means you use IO class to do what usually? 2,Should I learn all the IO package's classes? Or which classes are the keys I should learn strongly? Which classes are mostly useful? 3,I don't understand the "stream" very much, What do you think of the "stream"? Would you give me so examples to explain? 4,Would you please give me some advices fo learning java.IO? Thank you very much in advance.. : )
  • 4. Converting movies to JMF friendly format
    Dear all, I need to convert some movies to a format that can be played back with the java media framework. Even though I am following the cheat sheet for formats and am limiting myself to those playable by the cross-platform version, I am having difficulties. For example, trying to play back a QuickTime movie with H261 and Alaw audio. However, when I try to play it back, I get an array out of bounds exception in an ibm sourced package for H261. Could anyone recommend a video format (including audio and video compression) that they know works with the JMF. I'm using Adobe Premier to convert the video files. Ben

Problem with FileWriter class

Postby nimmi_srivastav » Tue, 22 Jul 2003 00:58:10 GMT

rief:- I am having trouble getting a FileWriter to write to a
non-existent file if I instantiate the FileWriter with a String that
is manipulated at run time. It works fine with a hard-coded char
array. The error that I get in the former case is:
(The specified path is invalid)tion



Detailed:- This is my first serious foray into Java ----- I recently
completed the Hello World program ----- so my apologies if I am not
doing things the right way (which, I am sure is the case).


I am trying to write a Java application that reads a list of URLs from
a file and accesses each URL and stores it associated web-page locally
on the file system. The filename associated with each webpage is the
same as its URL except that the following characters are replaced by
the '^' character:
\
/
:
*
?
<
|


I am not getting any error if I uncomment the line that says
//[UNCOMMENT ME] and comment the immediately preceding line (which
says [COMMENT ME]).

I was also able to successfully get the application to work by
maintaining an array of hard-coded strings and indexing into that
array for each iteration of the main loop.


Here's the program listing. Again my apologies for not doing things
the "right" way:


=======================Program Listing begin ==================


import java.net.*;
import java.io.*;

public class URLDownloader
{
public static void main(String[] args) throws Exception
{
if(args.length == 0)
{
System.out.println("usage: <this-utility> <filename>");
System.out.println("Exiting.....");
return;
}


File inputFile = new File(args[0]);

FileInputStream finStm = new FileInputStream(inputFile);
int ret;

StringBuffer urlAddr = new StringBuffer("");
char c;

DataInputStream inStm = null;

try
{
while ((ret = finStm.read()) != -1)
{
if((c = (char) ret) != '\n')
{
urlAddr.append(c);
continue;
}

System.out.println(urlAddr);
int len = urlAddr.length();
if(len <= 1)
continue;

URL thisURL = new URL(urlAddr.toString());
try
{
inStm = new DataInputStream(thisURL.openStream());
}
catch (Exception xcpn)
{
// FileNotFoundException, ProtocolException,
ConnectionException
urlAddr.delete(0, len);
System.out.println("Error: " + xcpn.toString());
continue;
}

String urlAddrStr = new String(urlAddr);
StringBuffer urlFile = new StringBuffer(urlAddrStr);
for(int i=0; i < urlFile.length(); i++)
{
char ch = urlFile.charAt(i);
switch(ch)
{
case '/':
case '\\':
case ':':
case '*':
case '?':
case '\"':
case '<':
case '>':
case '|':
urlFile.setCharAt(i, '^');
break;

default:
break;
}
}

String fileName = new String(urlFile);
System.out.println(fileName);
FileWriter fWriter = new FileWriter(fileName); // [COMMENT ME]
//[UNCOMMENT ME] FileWriter fWriter = new
FileWriter("http^^^www.yahoo.com");

String inputLine;

while ((inputLine = inStm.readLine()) != nul

Re: Problem with FileWriter class

Postby FGB » Tue, 22 Jul 2003 03:20:22 GMT



It worked ok for me.  I uncommented the line that creates fileName(s) 
and used the a "data file" with the following URLs:

 http://www.**--****.com/ 
 http://www.**--****.com/ 



Not sure what is happening for you...


Fred Burkley


Re: Problem with FileWriter class

Postby Steve Horsley » Tue, 22 Jul 2003 05:57:32 GMT



<snip>

I suspect you have the wrong file name. Instead of using:
    System.out.println(fileName);
try using:
    System.out.println("fileName = '" + fileName + "'");
This should show up any unexpected characters such as '\r'.

If you want to read a text file, you would be better off treating it as a
text file and using a Reader. This way you will more likely get the
characterset right, and handle line endings better.


Steve


Re: Problem with FileWriter class

Postby nimmi_srivastav » Fri, 25 Jul 2003 04:02:49 GMT






Since the original posting, I have tried this program on Solaris.  It
works fine on Solaris, but on Windows (98 & 2000) I keep getting error
messages.  Could someone kindly try it out on Windows and share their
experience please?

--NS

Re: Problem with FileWriter class

Postby sandeep6699 » Thu, 07 Aug 2003 19:56:06 GMT




Nimmi,

I tried your program on Solaris and Windows, and I ran into similar
problems on Windows.  It worked fine on Solaris.

Regards,
Sandeep

Re: Problem with FileWriter class

Postby weichao_wang » Tue, 19 Aug 2003 21:36:59 GMT



Replace the code above with the following, it may work on Windows:

        if((c = (char) ret) != '\r')
        {
          urlAddr.append(c);
          continue;
        } else {
          ret = finStm.read();  // skip '\n'
        }

The reason is that the line end is '\n' on Unix whereas it is '\r\n'
on Windows/DOS.
I have not tested the code (because of firewall?). If someone has tested
it, please post the result here.

Weichao

Re: Problem with FileWriter class

Postby nobody » Wed, 20 Aug 2003 14:47:41 GMT

Roedy Green < XXXX@XXXXX.COM > writes:

Roedy, if you look at the original, very old posting, you will see that
the problem is not the FileWriter. There are a number of problems in
the original code, including:

- Using an InputStream and not a Reader to read some text file

- Doing line-by-line reading via the InputStream with a home-made EOL
  detection that will break on any file not using the Unix convention,
  instead of using a LineReader.

- Usage of a DataInput stream for reading from a URL, serving no
  apparent purpose other then messing up the input data.

- Improper handling of empty lines (might be an artefact of the
  problems with handling EOL).

- Rather strange mixture of using String and StringBuffer, including
  converting a StringBuffer to a String and back to a StringBuffer on
  the next line, multiple times converting the same StringBuffer (with
  the same contents) to a String, etc.

- Improper attempt to convert a URL to a local file name (here the
  broken EOL detection can sneak control chars into the name, and some
  valid URL chars are not handled at all, like '=', '&', or '%').

  And the control char \r from the name is why the creation of the
  FileWriter breaks.

- Usage of the deprecated DataInputStream.readLine() to read a String.

- Usage of FileWriter to write bytes - which have just been converted
  from the String gotten from DataInputStream.readLine() ...

- Manual memory handling: Manually clearing existing objects instead of
  just creating new ones.

And I might have missed a few things.

In other words: THAT CODE DESERVES TO BE TAKEN OUT AND SHOT! The
remains have to be treated as toxic waste. Please, leave it alone.

/Thomas

Similar Threads:

1.Problem with FileWriter

Hi:

I'm writing a simple Web application that gets image data from a
third-party applet and writes it to a specified directory on a Web
server (this is done using a JSP and a JavaBean handling the file
upload.)

When I upload any *.jpg and attempt to write it to the server,
however, the size of  the copied image on the server directory is
exactly the same, but when I try to open the file, I get "No Preview
Available" from Windows Picture and Fax Viewer, "Can't determine type"
from Microsoft Photo Editor, etc.

Here is the code that I used to read from the applet source and write
to the server:


try {	
        // get the image input from applet
      	ServletInputStream in = request.getInputStream();
      	FileOutputStream ostrm = new FileOutputStream("picture4.jpg");
      	
      	byte[] readArray = new byte[1];       	
      	while((in.read(readArray)) != -1)
      	{
      		ostrm.write(readArray); 
      	}
      	// close all streams
      	in.close();
      	ostrm.close();
      	
	return true;
      } catch (Exception e) {
      	System.out.println("check console");
      	return false;
      }
	   
	}

Can anyone help me out?

2.FileWriter Problem

I get problem using FileWriter when I insert "/n" in it .It shows some
ugly square instead of going to the new line
I tried following code
***********************************************************************
import java.io.*;
class Writer
{
	public static void main(String args[])
	{
		
		String str ="Rahul is writing this piece\n"
			         +"I know that black square will come in place of newline
character\n"
			          +"I there anybody who can help me\n";
		char [] ch = new char[str.length()];
			str.getChars(0,str.length(),ch,0);
		try
		{
			FileWriter fw =new FileWriter("testfile.txt");
			fw.write(ch);
			fw.close();
		}
		catch(IOException ioe){}
	}
}
**********************************************************************
Please help in case you have a solution to this problem
Thanking in anticipation
Rahul Sharma
 XXXX@XXXXX.COM 

3.problem writing doubles with java filewriter

I can write strings fine but can't write doubles. Do I have to close
the file and try writing with another method?

4.FileWriter.write() does not fail if file is removed after being opened

Greetings!
This may be an OS thing, but FileWriter.write(Sting,int,int) thinks it
is writing ok when I remove the file it is writing to after the file
has been opened.  No exception is thrown, because the line directly
after the write() and flush() within the try block is executed (I am
catching Exception if that matters).  I am speculating that the OS is
not notifying the owner of the file handle (if I an saying it right)
that the file has been deleted / removed / whatever, and that this
might function differently on different systems.

I am trying to create a failover for a log writing thread, and I am
removing the file to simulate an IO error, hehe but that's not
working.  Is there a) a better way to simulate an IO error?  and b) a
more primitive write method that might throw an exception in this
unlikely circumstance?

Thanx!

clh

5.java.io.FileReader and java.io.FileWriter encoding

Hi,

I recently changed the hosting for my website (from Linux to Linux) and 
now I'm experiencing some trouble with java.io.FileReader and 
java.io.FileWriter: their getEncoding() method returns ASCII (returned 
ISO8859_1 on the previuos host). I've set -Dfile.encoding=ISO-8859-1 but 
nothing has changed, except that 
javax.mail.internet.MimeUtility.getDefaultJavaCharset() effectively 
returns ISO-8859-1.

Does anyone know how the default encoding is selected? I report some 
system properties:

file.encoding.pkg: sun.io
user.country: US
java.runtime.version: 1.4.2_04-b05
os.version: 2.4.27
user.timezone: America/New_York
file.encoding: ISO-8859-1
user.language: en
java.version: 1.4.2_04
java.vendor: Sun Microsystems Inc.

-----
Mario

6. Absolute path / creating FileWriter-object

7. FileWriter and Path

8. Cant find java.io.FileWriter?



Return to JAVA

 

Who is online

Users browsing this forum: No registered users and 91 guest