I need to upload and read a text file with PrimeFaces and JSF. My question is that when I uploaded the text file, where is it stored?
Here is my .xhtml file:
<p:fileUpload value="#{send.file }" mode="simple" />
</h:form>
<p:commandButton actionListener="#{send.upload}" value="Send" ajax="false" />
And Java class:
public class Send {
private UploadedFile file;
public void upload() {
if (file != null) {
FacesMessage msg = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
I also found this example to read the file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
My other question is in this example "C:\\testing.txt" is given as a path? Which address I must give to read my uploaded file?
when I uploaded the text file, where is it stored?
This is actually none of your business and you should not be interested in that from inside your JSF backing bean code. It's stored (partial) in memory and/or (partial) in server's temporary storage location which will be wiped/cleaned at intervals. It's absolutely not intented as permanent storage location. You should in the action/listener method just read the uploaded file content and store it in the permanent storage location to your choice.
E.g.
private static final File LOCATION = new File("/path/to/all/uploads");
public void upload() throws IOException {
if (file != null) {
String prefix = FilenameUtils.getBaseName(file.getName());
String suffix = FilenameUtils.getExtension(file.getName());
File save = File.createTempFile(prefix + "-", "." + suffix, LOCATION);
Files.write(save.toPath(), file.getContents());
// Add success message here.
}
}
Note that the FilenameUtils is part of Apache Commons IO which you should already have installed as it's a required dependency of <p:fileUpload>. Also note that File#createTempFile() does in above example not exactly generate a temp file, but it's just been used to generate an unique filename. Otherwise, when someone else coincidentally uploads a file with exactly the same name as an existing one, it would be overwritten. Also note that Files#write() is part of Java 7. If you're still on Java 6 or older, grab Apache Commons IO IOUtils instead.
please take a look at this thread that is related to the same issue:
how to upload file to http remote server using java?.
Please if it does not help you, let me know, and I will go through. ;)
I red the file this way
private UploadedFile file;
public void upload() {
if (file != null && !"".equals(file.getFileName())) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputstream(), "UTF-8"))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception ex) {
LOG.error("Error uploading the file", ex);
}
}
}
Related
I'm trying to upload zip file to the url https://anypoint.mulesoft.com/designcenter/api-designer/projects/{projectId}/branches/master/import. Content-Type must be application/zip, cant change to multipart/form-data. In Mule 3, a java transform class is used (com.test.FileReader) with the FileReader.class is stored in lib. It worked in Mule 3.
I tried to use ReadFile component to read test.zip and set as payload but it's not working. Any suggestion how to upload zip file in Mule 4?
package com.test;
import org.mule.transformer.*;
import org.mule.api.*;
import org.mule.api.transformer.*;
import java.io.*;
public class PayloadFileReader extends AbstractMessageTransformer
{
public Object transformMessage(final MuleMessage message, final String outputEncoding) throws TransformerException {
byte[] result = null;
try {
result = this.readZipFile("test.zip");
}
catch (Exception e) {
e.printStackTrace();
}
message.setPayload((Object)result);
return message;
}
public String readFileTest(final String path) throws FileNotFoundException, IOException, Exception {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final FileReader fileReader = new FileReader(file);
BufferedReader bufferReader = null;
final StringBuilder stringBuffer = new StringBuilder();
try {
bufferReader = new BufferedReader(fileReader);
String line;
while ((line = bufferReader.readLine()) != null) {
stringBuffer.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
finally {
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e2) {
e2.printStackTrace();
}
}
}
return stringBuffer.toString();
}
public byte[] readZipFile(final String path) {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final byte[] b = new byte[(int)file.length()];
try {
final FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
fileInputStream.close();
}
catch (FileNotFoundException e) {
System.out.println("Not Found.");
e.printStackTrace();
}
catch (IOException e2) {
System.out.println("Error");
e2.printStackTrace();
}
return b;
}
}
'
Assuming that your zip file corresponds to a valid API spec, in Mule 4, you don't need to use a custom java code to achieve what you want: you can read the file content using the File connector Read operation, and use an HTTP Request to upload it to Design Center using Design Center API. Your flow should look like:
For the Read operation, you only need to set the file location, in the File Path operation property.
No need to set content type in the HTTP Request (Mule 4 will configure the content type automatically based on the file content loaded by the Read operation).
You can't use Java code that depends on Mule 3 classes in Mule 4. Don't bother trying to adapt the code, it is not meant to work. Their architecture are just different.
While in Mule 4 you can use plain Java code or create a module with the SDK, there is no reason to do so for this problem and it would be counterproductive. My advise it to forget the Java code and resolve the problem with pure Mule 4 components.
In this case there doesn't seem a need to actually use Java code. The File connector read operation should read the file just fine as it doesn't appear the Java code is doing anything else than reading the file into the payload.
Sending through the HTTP Request connector should be straightforward. You didn't provide any details of the error, (where is it happening, complete error message, HTTP status error code, complete flow with the HTTP request in both versions, etc) and the API Designer REST API doesn't document an import endpoint so it is difficult to say if the request is correctly constructed.
I am using Netbeans on OS X and cannot seem to write text to a text file that I have in a package named "assets".
Below is the way I tried to accomplish writing to the text file and so far my method of doing this is not working.
The way I tried to approach this problem was converting a string to url, then converting the url to a uri. Then I used the uri for the new file parameter. After I tried to write a string using the class print writer.
public class Experiment {
File createFile(String path) {
java.net.URL url = getClass().getResource(path);
URI uri;
try {
uri = url.toURI();
}
catch (URISyntaxException e) {
uri = null;
}
if ((url != null) && (uri != null)) {
System.out.println("file loading sucess");
return new File(uri);
}
else {
System.out.println("Error file has not been loaded");
return null;
}
}
File file = createFile("/assets/myfile.txt");
public static void main(String[] args) {
Experiment testrun = new Experiment();
try {
PrintWriter writer = new PrintWriter(new FileWriter(testrun.file));
writer.println("it works");
writer.flush();
writer.close();
System.out.println("string was written");
}
catch (IOException e) {
System.out.println("there was an error while writing");
}
}
}
The output given from my try catch statements say that the file write code was executed.
file loading sucess
string was written
BUILD SUCCESSFUL (total time: 2 seconds)
I have also tried using absolute string paths for making a new file, but with null results. I am running out of ideas and hoping for some guidance or solution from somebody.
I have put a file "template.html" inside RAW folder and I want to read it into a InputStream. But it is returning me null. Can't understand what is wrong in the below code
e.g. fileName passed as parameter is "res/raw/testtemplate.html"
public String getFile(String fileName) {
InputStream input = this.getClass().getClassLoader().getResourceAsStream(fileName);
return getStringFromInputStream(input);
}
Also, there might be a better solution by putting these files in a particular subfolder and putting it inside Asset folder but then I believe I would need to pass context in AssetManager. I don't understand that solution, sorry I am new to android development. Can someone shed some light regarding how this approach can be achieved.
EDIT
I have started implementing this solution with Assets. Below method is supposed to return a string containing the entire text of the file stored as template.html.
getFile("template.html") // I am sending extension this time
Problem getting error getAssets() is undefined.
public String getFile(String fileName) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
String line;
try {
reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
use this
new BufferedInputStream(getResources().openRawResource(filepath));
this will return a buffered input stream
The file name should be without extension :
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("raw/FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName()));
For this purposes uses assets folder:
assets/
This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.
So, you could easy get access at assets with context: context.getAssets()
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("filename.txt")));
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
I new to developing in android but I'm not in java. So I want to develop an app that checks for football match scores and as soon as new data is available the android app must push that data to the user in a notification fashion.
My question is the following:
Can I use a website's server that is not mine to get data from since I dont have a server to use. Therefore I cant use C2DM
If not what is the solution to this: TCP/IP connection or can I customize a webview to my liking?
Thanks in advance,
Roy
My experience with using internet data, however this may help you start.
This is the class that I use to download webpages and return them as a string, it should be possible to parse the page data to extract the data that you want. Something you should be careful is that it can be common for webpages to change their format which could break your parsing functionality, perhaps without you even realising.
Check this out for Java HTML parsers
package AppZappy.NIRailAndBus;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Simplifies downloading of files from the internet
*/
public class FileDownloading
{
/**
* Download a text file from the Internet
* #param targetUrl The URL of the file to download
* #return The string contents of the files OR NULL if error occurred
*/
public static String downloadFile(String targetUrl)
{
BufferedReader in = null;
try
{
// Create a URL for the desired page
URL url = new URL(targetUrl);
// Read all the text returned by the server
in = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder sb = new StringBuilder(16384); // 16kb
String str = in.readLine();
if (str != null)
{
sb.append(str);
str = in.readLine();
}
while (str != null)
{
// str is one line of text; readLine() strips the newline
// character(s)
sb.append(C.new_line());
sb.append(str);
str = in.readLine();
}
String output = sb.toString();
return output;
}
catch (MalformedURLException e)
{}
catch (IOException e)
{}
finally
{
try
{
if (in != null) in.close();
}
catch (IOException e)
{
}
}
return null;
}
private FileDownloading()
{}
}
I had posted a question in regards to this code. I found that JTextArea does not support the binary type data that is loaded.
So my new question is how can I go about detecting the 'bad' file and canceling the file I/O and telling the user that they need to select a new file?
class Open extends SwingWorker<Void, String>
{
File file;
JTextArea jta;
Open(File file, JTextArea jta)
{
this.file = file;
this.jta = jta;
}
#Override
protected Void doInBackground() throws Exception
{
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null)
{
publish(line);
line = br.readLine();
}
}
finally
{
try
{
br.close();
} catch (IOException e) { }
}
return null;
}
#Override
protected void process(List<String> chunks)
{
for(String s : chunks)
jta.append(s + "\n");
}
}
You could cover the most by sniffing the mime type based on the file extension or, even better, the actual file content. You can do that with help of among others jMimeMagic (Maven coords here). If the mime type does not start with "text", then it's certainly not a text file.
String mimeType = Magic.getMagicMatch(file, false).getMimeType();
boolean text = mimeType.startsWith("text");
I found that MIME types can really help with this!
JAF
For those who read this and are curious as to what I have done to fix the File reading problem.... I have instead implemented a FileReader and have experienced no problems on Windows. I have however noticed on Linux that there are some problems which tends to lead to a crash. Also I noticed when running through an IDE such as Netbeans I receive various runtime errors when trying to load a binary file and massive slow-down; but when I execute the .jar as an executable and not from the IDE it works fine.
Here is relevant code that I have had no problem with (even when loading binary file types such as .mp3, .exe, etc.)
/*...*/
#Override
protected Void doInBackground() throws Exception {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
int ch = br.read();
while(ch != -1) {
publish(ch);
ch = br.read();
}
}
finally {
try {
br.close();
} catch (IOException e) {}
}
System.gc();
return null;
}
/*...*/