Hi there I want to read out a file that lies on the server.
I get the path to the file by a parameter
<PARAM name=fileToRead value="http://someserver.de/file.txt">
when I now start the applet following error occurs
Caused by: java.lang.IllegalArgumentException: URI scheme is not "file"
Can someone give me a hint?
BufferedReader file;
String strFile = new String(getParameter("fileToRead"));
URL url = new URL(strFile);
URI uri = url.toURI();
try {
File theFile = new File(uri);
file = new BufferedReader(new FileReader(new File(uri)));
String input = "";
while ((input = file.readLine()) != null) {
words.add(input);
}
} catch (IOException ex) {
Logger.getLogger(Hedgeman.class.getName()).log(Level.SEVERE, null, ex);
}
File theFile = new File(uri);
is not the correct method. You accessing an URL, not a File.
Your code should look like this:
try
{
URL url = new URL(strFile);
InputStream in = url.openStream();
(... read file...)
in.close();
} catch(IOException err)
{
(... process error...)
}
You are trying open as a file, something which doesn't follow the file:// uri, as the error suggests.
If you want to use a URL, I suggest you just use url.openStream() which should be simpler.
You will need to sign the applet unless the file is being accessed from the same server/port that the applet came from.
Related
My else if block will verify the result from remote service.
If the result matches, it will trigger another API call to contact the remote service again. The remote service will send back a file to my client program.
I tested all my code and it is working but I am not able to open back the new file and it's showing the file was corrupted. My client program will read the file from the remote service and write it into another file name in a different directory.
This is my source code:
else if (result == 1 && value.equals("problem"))
{
String Url = "http://server_name:port/anything/anything/";
String DURL = Url.concat(iD);
System.out.println("URL is : " + DURL); // the remote API URL
URL theUrl = new URL (DURL);
HttpURLConnection con1 = (HttpURLConnection) theUrl.openConnection(); //API call
con1.setRequestMethod("GET");
con1.connect();
int responseCode = con1.getResponseCode();
if(responseCode == 200)
{
try
{
InputStream is1 = con1.getInputStream();
BufferedReader read1 = new BufferedReader (new InputStreamReader(is1));
String data1 = "" ;
while ((data1 = read1.readLine()) != null)
{
PrintStream ps = new PrintStream(new FileOutputStream(filePath));
ps.print(data1);
ps.close();
}
System.out.println("The new sanitized file is ready");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
This is my filePath mentioned in the code D:/file/red_new.docx. This is how I get my file path: String filePath = "D:/file/"+fn+"_new."+fileType;. The fn variable is the filename from the JSON string from the first API call while the fileType is the file type from the JSON string from the second API call. I add in the _new to indicate it's a new file and using java concatenate with the fn and fileType to obtain the full path.
You're creating a new output file per line of input, so you'll only ever get the last line. And you're also losing the line terminators. Try this:
PrintStream ps = new PrintStream(new FileOutputStream(filePath));
while ((data1 = read1.readLine()) != null)
{
ps.println(data1);
}
ps.close();
You're also not closing the input stream.
If these files aren't all known to be text files you should be using InputStream and OutputStream.
Please use finally block to close the open streams. If stream is not closed, you can't open it until the process holding the stream is closed or released.
eg:
try( InputStream is1 = con1.getInputStream()){
// ...
}
Following is my code to read the file and rename it afterwards. Im using apache commons.net 3.0.1.
client.connect(localhost);
boolean login = client.login("username", "password");
if(login){
System.out.println("login successful");
boolean chdir = client.changeWorkingDirectory("/home/folder1/child/");
String url = client.printWorkingDirectory(); // EDIT
FTPFile[] result = client.listFiles(url, filter);
if (result != null && result.length > 0) {
for (FTPFile aFile : result) {
try{
String filename = aFile.getName();
InputStream is= client.retrieveFileStream(filename);
br = new BufferedReader(new InputStreamReader(is));
while((line = br.readLine()) != null){
System.out.println("the line is"+line);
}
}
finally{
if(br!=null){
try{
br.close();
String oldFilename =url + "/" +aFile.getName();
String newFilename = "PRO"+aFile.getName();
boolean rename = client.rename(oldFilename, newFilename);
if(rename){
System.out.println("renamed");
}
else{
System.out.println("Error in renaming");
}
}
The file deosn't get renamed and the program prints
error in renaming files (cz boolean rename = false).
I have refereed to different examples. But all seems to show the same problem.
The file is picked after filter and read without any issues.
If anyone could point to what I'm doing wrong here, that'd be very helpful.
Here, the url is String url = client.printWorkingDirectory();
I have tried with both relative path and absolute path. And giving full path only to the oldFilename and just the filname to the newFilename. Both did not work.
EDIT
Before changing the directory, the url will be / which is root.
After changing the directory, the url will be /home/folder1/child/. This is the where the files exists.
InputStream retrieveFileStream(String remote):This method returns an InputStream which we can use to read bytes from the remote file. This method gives us more control on how to read and write the data. But there are two important points when using this method:
The method completePendingCommand() must be called afterward to finalize file transfer and check its return value to verify if the download is actually done successfully.
boolean success = ftpclient.completePendingCommand();
if (success){
System.out.println("File #2 has been downloaded successfully.");
}
We must close the InputStream explicitly.
is.close(); //is = InputStream
SOURCE
When I read a file from the jar file and want to put it in in a jTextArea, it shows me crypted symbols, not the true content.
What I am doing:
public File loadReadme() {
URL url = Main.class.getResource("/readme.txt");
File file = null;
try {
JarURLConnection connection = (JarURLConnection) url
.openConnection();
file = new File(connection.getJarFileURL().toURI());
if (file.exists()) {
this.readme = file;
System.out.println("all ok!");
}
} catch (Exception e) {
System.out.println("not ok");
}
return file;
}
And then i read the file:
public ArrayList<String> readFileToArray(File file) {
ArrayList<String> array = new ArrayList<String>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
String test = sCurrentLine;
array.add(test);
}
} catch (IOException e) {
System.out.println("not diese!");
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
}
}
return array;
}
Now, i put all lines from the ArrayList in the jTextArea, that showes me things like that:
PK����?����^��S?��3��� z_��
%�Q Tl?7��+�;�
�fK� �N��:k�����]�Xk,������U"�����q��\����%�Q#4x�|[���o� S{��:�aG�*s g�'.}���n�X����5��q���hpu�H���W�9���h2��Q����#���#7(�#����F!��~��?����j�?\xA�/�Rr.�v�l�PK�bv�=
The textfiled contains:
SELECTION:
----------
By clicking the CTRL Key and the left mouse button you go in the selection mode.
Now, by moving the mouse, you paint a rectangle on the map.
DOWNLOAD:
---------
By clicking on the download button, you start the download.
The default location for the tiles to download is: <your home>
I am sure that the file exists!
Does anyone know what the problem is? Is my "getResource" correct?
Based on the output, I'm suspecting your code actually reads the JAR file itself (since it starts with PK). Why not use the following code to read the text file:
Main.class.getResourceAsStream("/readme.txt")
That would give you an InputStream to the text file without doing the hassle of opening the JAR file, etc.
You can then pass the InputStream object to the readFileToArray method (instead of the File object) and use
br = new BufferedReader(new InputStreamReader(inputStream));
The rest of your code should not need any change.
This seems to be an encoding problem. FileReader doesn't allow you to specify that. Try using
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), yourEncoding));
You seem to be making far too much work for yourself here. You start by calling getResource, which gives you a URL to the readme.txt entry inside your JAR file, but then you take that URL, determine the JAR file that it is pointing inside, then open that JAR file with a FileInputStream and read the whole JAR file.
You can instead simply call .openStream() on the original URL that getResource returned, and this will give you an InputStream from which you can read the content of readme.txt
br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
(if readme.txt is not encoded in UTF-8 then change that parameter as appropriate)
I created some code to handle basic file upload from a java client to a php server, but I'm having some issues with the naming and directory creation. Here is the important parts of the code:
The method I use to upload the file:
public static void uploadWithInfo(Uri uri, String title, String artist, String description) {
try {
String path = uri.getPath();
File file = new File(path);
URL url = new URL("http://**********/upload.php?title="+title+"&artist="+artist+"&description="+description);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int totalbytes = bis.available();
for(int i = 0; i < totalbytes; i++) {
os.write(bis.read());
}
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String serverResponse = "";
String response = "";
while((response = reader.readLine()) != null) {
serverResponse = serverResponse + response;
}
reader.close();
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
It's just supposed to upload an audio file. The user inputs the artist, title, and a very short description if necessary. The actual file is uploaded just fine so I don't think any more java is necessary. Here is the code on the php end:
<?php
$uploadBase = "music/";
$uploadFolder = $_GET['artist']+"/";
$uploadFileName = $_GET['title'];
$uploadFileDescription = $_GET['description'];
$uploadPath = $uploadBase.$uploadFolder.$uploadFileName."%%D%%=".$uploadFileDescription.".mp3";
if(!is_dir($uploadBase)) {
mkdir($uploadBase);
}
if(!is_dir($uploadFolder)) {
mkdir($uploadFolder);
}
$incomingData = file_get_contents('php://input');
if(!$incomingData) {
die("No data.");
}
$fh = fopen($uploadPath, 'w') or die("Error opening path.");
fwrite($fh, $incomingData) or die("Error writing file.");
fclose($fh) or die("Error closing shop.");
echo "Success!";
?>
So I get all of the inputted values for title, artist, and description. Then I create 2 directories if they don't already exist: one for music and one for the artist the uploader input. Then I create a path of base(music)/folder(artist)/filename(title)"code to let me parse description"(%%D%%).mp3.
So a song Billie Jean by Michael Jackson with a description "favorite" should have a path of
music/Michael Jackson/Billie%20Jean%%D%%favorite.mp3
What I get however, is:
music/0Billie%%D%%=
The directory for artist is not created, there is a weird 0 before the title (which only includes the first word), and the description doesn't show.
I don't really know where I went wrong, can anyone give me some insight? Thank you.
Your InputStream.available() method does not do what you expect it to. Use the File size instead.
Edit:Use a multi-part upload instead. The Apache HttpClient supports it, google for examples.
Turns out it was a stupid error with some related php code. Sorry to trouble you all.
In my aplication i want to send a html template to the users email. Everithing works correctly when i programatically create the html, but what i want to do now, is read the html text from within a file in my application and send it. I get a FileNotFoundException, and i dont know how to find that .txt file. See the code:
public void sendAccountActivationLinkToBuyer(String destinationEmail,
String name) {
// Destination of the email
String to = destinationEmail;
String from = "myEmail#gmail.com";
try {
Message message = new MimeMessage(mailSession);
// From: is our service
message.setFrom(new InternetAddress(from));
// To: destination given
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Registration succeded");
// Instead of simple text, a .html template should be added here!
message.setText(generateActivationLinkTemplate());
Date timeStamp = new Date();
message.setSentDate(timeStamp);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private String generateActivationLinkTemplate() {
String htmlText = "";
try {
File f = new File("");
BufferedReader br = new BufferedReader(new InputStreamReader(f.getClass().getResourceAsStream("./web/emailActivationTemplate.txt")));
String content = "";
String line = null;
while ((line = br.readLine()) != null) {
content += line;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return htmlText;
}
The second method is giving me problems, i cant find that .txt file. What should i do?
I created the folder web inside the WebContent folder,the web folder is now located right next to META-INF and WEB-INF(I think that is an appropiate place to hold my images, templates,css...) Inside the folder i manually pasted the emailActivationTemplate.txt Now i need to read from it. Any ideas?
This is the console output:
SEVERE: java.io.FileNotFoundException: .\web\emailActivationTemplate.txt (The system cannot find the path specified)
Put emailActivationTemplate.txt in WEB-INF/classes, and get it with
BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResource("emailActivationTemplate.txt"));
(String) System.getProperties().get("com.sun.aas.instanceRoot")
Your emailActivationTemplate.txt should be present inside the classes folder of WEB-INF. If you manage to place it there, you should be able to read it using:
BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("/emailActivationTemplate.txt")));
Try without the leading '/' if it doesn't work.