Require to read a flat file that do not have any extension through URL, couldn't get this as browser(404) and java(FileNotFoundException) not taking the file as a resource to open.
import java.net.*;
import java.io.*;
public class URLTest {
public static void main(String[] args) {
/*Block 1: Reading a file "test.txt" (WITH extension) that works */
try{ System.out.println("Block 1");
URL url1 = new URL("http://localhost:8080/CtxPath/test.txt"); //file test.txt available at WebContent
BufferedReader in = new BufferedReader(new InputStreamReader(url1.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch(Exception e) { e.printStackTrace(); }
/* Block 2 : Reading the other one "test" (WITHOUT extension) that throws Exception */
try{ System.out.println("Block 2");
URL url2 = new URL("http://localhost:8080/CtxPath/test"); ////file test also available at WebContent
BufferedReader in = new BufferedReader(new InputStreamReader(url2.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch(Exception e) { e.printStackTrace(); }
}
}
Output
Block 1
File content from test.txt read successfully.
Block 2
java.io.FileNotFoundException: http://localhost:8080/CtxPath/test
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1624)
at java.net.URL.openStream(URL.java:1037)
at URLTest.main(URLTest.java:28)
Jboss 5.1 Java 1.7
Getting exception on open URL for the file(test) without extension. The other file with .txt extension(test.txt) that placed in the same location with similar content opens without any issues.
Is there any app specific or server specific config to do for allowing the file without extension to be served?
In the servlet container implementation, things without suffix "test" is not treat as file, but treat as servlet mapping.
You can download tomcat source code, the logic for this is similar in jboss, and take a look.
And I don't think you should make a file without suffix, if you really need to, then put it under WEB-INF/xxx/, then use a servlet to help read it.
Java is simply calling the URL. It cares not whether it has a . in the path. The server you are calling, on the other hand, /may/ have logic which determines how it attempts to fulfill the request. The FileNotFoundException indicates a 404 http status code was returned.
It may be possible that file does have extension that you may not be able to see because Operating system settings have hide the extensions or some rules on your server may causing it to return 404. Java does not give file not found exception because of extension.
Please let us know the issue, when you resolve it.
Related
I do have two questions where one would be solved after the first question.
1) I want to open simple URL in my company laptop with java but it does not let me open it. It gives connection timed out error. Would it be cause of the network settings that I need to make them in my java code also ? When I click the IE settings on LAN, there is no proxy settings but the configuration part is clicked and there is an adress http://wgate.company.entp.tgc:8080/wpad.dat . Please let me know what I need to do in java code.
My sample code
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.google.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
2) I do have a list of link pages to download Word files. I want to make a loop in java and I want java to go to these web pages and download files at once instead of me. Is there any special function or code to download a file in java ?
Thank you.
sample url I have
http://www.gooogle.com/attachments/change/TestCase_F257579.doc
I am trying to create a Java Applet that outputs information to a text file located in the same directory as the java applet. I understand Java Applets are not ideal, but I have spent a great deal of time on this and if possible want to solve this through applets. Here is some of my code on how I could read code from a file into a text box. I assume it would be something similar to this, but outputted.
public void readFile() {
String line;
URL url = null;
try {
url = new URL(getCodeBase(), fileToRead);
}
catch(MalformedURLException e) {
}
try {
InputStream in = url.openStream();
BufferedReader bf = new BufferedReader
(new InputStreamReader(in));
strBuff = new StringBuffer();
while((line = bf.readLine()) != null){
strBuff.append(line + "\n");
}
a1.append("File Name : " + fileToRead + "\n");
a1.append(strBuff.toString());
}
catch(IOException e) {
e.printStackTrace();
}
}
If you want an applet to store data on the local machine, from 6u10 the javax.jnlp.PersistenceService is available.
or on your local machine...
java.io.File file = new java.io.File(System.getProperty("user.home"), "yourfile.txt");
You must have it signed, otherwise...
Keep in mind that from an Applet, you cannot directly write to the server's file system. You can issue a request to the server that causes the server to write to its own file system, but an Applet does not have a way to write to a file system on a remote machine.
A signed Applet has every right to write to the local file system of the person running the Applet. If you are writing to the "current directory" (rather than an absolute full path), then make sure you know what directory the Applet is running in. Otherwise you may indeed create a file, but not be able to find it!
EDIT
Signed Applet Tutorial
So what I am trying to achieve is reading the contents of a .txt file from a url:
BufferedReader reader = null;
File f = new File ("www.website.com/filename.txt");
if (f.exists()) {
try {
reader = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = "";
try {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Even though I have content in the .txt file (only one line), when I print the line nothing shows up. Is reading a file from a URL or from your hard drive different, or am I doing something wrong?
The File class is for files on a "normal" file system (usually local, but potentially networked) - not URLs. Basically it's for the sort of file you can use (e.g. read or edit) directly on a command line, with no HTTP involved1.
That's what the URL class is for. So you can either use that (with URLConnection) or use a dedicated HTTP 3rd party library, such as the Apache HttpClient library.
1 I'm sure there are some shells which allow the use of URLs as if they were local filenames, but I'm talking about a more traditional approach.
I tried own my own and this worked...
URL urlObj=new URL("http://www.example.com/index.html"); //This can be any website' index.html or an available file
//we basically get HTML page/file
Scanner fGetter=new Scanner(urlObj.openStream());
while(fGetter.hasNext()){
System.out.println(""+fGetter.nextLine());
}
And I think "example.com" can be used without any legal issues :)
I don't actually know but I don't think you can read a file from a URL like that. You need to send a HTTP GET request to that url to read the information in.
See object HttpURLConnection.
http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html
I'm using the acm libraries for my Java program, and I want to embed my program into my website via HTML. I have other .jar files embedded just fine in my website, by using the
<applet archive="file.jar, acm.jar"
code="main.class"
width=400 height=600 />
but have found that when embedded in HTML the program sort of freaks out and stops responding when it gets to the part where it should load the .txt file.
I remember vaguely my AP CompSci teacher telling us that java in web browsers blocked the import of .txt files, but I might be remembering incorrectly. Here is my java code below:
public NameSurferDataBase(String filename) {
nameEntry = new HashMap<String, NameSurferEntry>();
try {
BufferedReader rd = new BufferedReader(new FileReader(filename));
while (true) {
String line = rd.readLine();
if (line == null) break;
NameSurferEntry entry = new NameSurferEntry(line);
nameEntry.put(entry.getName().toUpperCase(), entry);
}
} catch (IOException ex) {
throw new ErrorException(ex);
}
}
So not only do I not know how to actually add the .txt file as something to use before it runs, I don't even know if it is possible.
It's because when running applets, the security manager doesn't let you work with the filesystem (unless you specifically change the plugin settings which is a bad idea). If you're just trying to read, put the file in your classpath, and use ClassLoader.getResourceAsStream(String resource) to get the input stream instead.
I create ImageServlet to refer to videos out of my web application scope.
The location of all of my videos are on a intranet location that could be reached from any computer in the intranet:
String path = "\\myip\storage\ogg\VX-276.ogg"
In my application, when I write it as URL - it can't display it!
If I try to open it with chrome it automatically changes it to file://myip/storage/ogg/VX-276.ogg and the file is being displayed.
I tried to do so: file:////odelyay_test64/storage/ogg/
as well but Java converts the string to: file:\myip\storage\ogg\VX-276.ogg which does not exist!
What is the correct way to refer to it?
EDITED
I create a small test:
String path = "file://myip/storage/ogg/VX-276.ogg";
File file = new File(path);
if (file.exists())
System.out.println("exists");
else {
System.out.println("missing" + file.getPath());
}
and I get:
missing file:\myip\storage\ogg\VX-276.ogg
As you can see the slashes are being switched
As per your previous question, you're referencing the resource in a HTML <video> tag. All URLs in the HTML source code must be http:// URLs (or at least be relative to a http:// URL). Most browsers namely refuse to load resources from file:// URLs when the HTML page is itself been requested by http://. You just need to let the URL point to the servlet. If the servlet's doGet() method get hit, then the URL is fine and you should not change it.
Your concrete problem is in the way how you open and read the desired file in the servlet. You need to ensure that the path in File file = new File(path) points to a valid location before you open a FileInputStream on it.
String path = "file://myip/storage/ogg/VX-276.ogg";
File file = new File(path);
// ...
If the servlet code is well written that it doesn't suppress/swallow exceptions and you have read the server logs, then you should have seen an IOException such as FileNotFoundException along with a self-explaining message in the server logs whenever reading the file fails. Go read the server logs.
Update as per the comments, it turns out that you're using Windows and thus file:// on a network disk isn't going to work for Java without mapping it on a drive letter. You need to map //myip on a drive letter first, for example X:.
String path = "X:/storage/ogg/VX-276.ogg";
File file = new File(path);
// ...
in the end I used VFS library of apache and my code looks like this:
public static void main(String[] args) {
FileSystemManager fsManager = null;
String path = "\\\\myip\\storage\\ogg\\VX-276.ogg";
try {
fsManager = VFS.getManager();
FileObject basePath;
basePath = fsManager.resolveFile("file:" + path);
if (basePath.exists())
System.out.println("exists");
else {
System.out.println("missing" + basePath.getURL());
}
} catch (FileSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In this way, I don't need to create a driver for each user of the system and it allows me not to depend on operation system!