JSP FileReader URL Issue - java

I get the strangest thing going on...
I have a JSP file which read a file from given path, but somehow the http:// is changed to http:\
BufferedReader in = new BufferedReader(new FileReader("http://server/path/file.sql"));
the exception i get is:
(the file exist for sure!!! works when url is entered in webrowser).
exception=http:\server\path\file.sql (The filename, directory name, or volume label syntax is incorrect)

Use new InputStreamReader(new URL("http://....").openStream(), "UTF-8")
FileReader is used to read the filesystem, not URLs. Also have in mind that writing java code in JSP is usually not a good idea. See here

Related

Why can't I get a file from resources?

Why can't I get a file from resources?
URL resource = getClass().getClassLoader().getResource("input data/logic test.csv");
System.out.println("Found "+resource);
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
CSVReader reader = new CSVReaderBuilder(new FileReader(resource.getFile())).withSkipLines(1).withCSVParser(parser).build();
Console output:
Found file:/home/alexandr/Repos/OTUS/first_home_work/target/classes/input%20data/logic%20test.csv
Exception in thread "main" java.io.FileNotFoundException: /home/alexandr/Repos/OTUS/first_home_work/target/classes/input%20data/logic%20test.csv (Нет такого файла или каталога)
There is an inherent logic problem with this line:
CSVReader reader = new CSVReaderBuilder(
new FileReader(resource.getFile()))..
Once the CSV is part of a Jar, it will no longer be accessible as a File object. But something like this should work directly for the URL.
CSVReader reader = new CSVReaderBuilder(
new InputStreamReader(resource.openStream()))..
change space for _ in directory name and file name, and working
This will only work while the resource is not in a Jar file.
It's:
try (InputStream raw = ClassThisIn.class.getResourceAsStream(""input data/logic test.csv")) {
InputStreamReader isr = new InputStreamReader(raw, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
// now use br as if it was your filereader.
}
This addresses many issues:
Still works regardless of how you're running it: Your snippet only works if running as straight class files (vs., say, in a jar), and doesn't work if spaces are involved.
Still works even if your class is subclassed (getClass().getClassLoader().getResource won't, which is why you should not do that).
Still works even if the platform local charset encoding is weird (the snippet in this answer is explicit about it. That's always a good idea).
Doesn't have a resource leak. Your code never safely closes the reader you open. If you open resources, either do so in a try-with-resources construct, or, store the resource in a field and implement AutoClosable.
i change space for _ in directory name and file name, and working.... omg.
The answer is in your console output - the file was simply not found.
I would try the same code you have written, but use a file without spaces in it - and see if the file is still not found.

Confused on getting the path for writing a text file using a Servlet

I've the below project structure in my eclipse.
and my code in servlet is as below.
File entityFile = new File(getServletContext().getContextPath() + "/EntityList/entities.txt");
FileWriter fout = new FileWriter(entityFile);
fout.write("The Content");
fout.close();
here basically I'm trying to write to a file available at /EntityList/entities.txt, but when I run this, I get the exception as below.
SEVERE: Servlet.service() for servlet
[com.luis.servlets.WriteEntityToAFile] in context with path
[/LUISWebUI] threw exception java.io.FileNotFoundException:
\LUISWebUI\EntityList\entities.txt (The system cannot find the path
specified)
I know that I'm going wrong with the path, Can someone please put me in the right direction.
Update
Apologies for the confusion.
I'm sending some data from jsp to servlet to write to the entities.txt file. I'm able to capture it in servlet(Cross checked it by doing sysout).
First of all I think you have a typo problem, try /EntitiesList/entities.txt instead of /EntityList/entities.txt.
Also, move the /EntitiesList/entities.txt under /WEB-INF/ for example, so that your servlet class can access it.
You can read a more detailed explanation in this SO answer.
Edit:
About writing to file: your application will be packaged inside a WAR file so you won't be able to write to it, only read from it (more about this here).
But you can just use this way of creating directly a file outside the WAR and using this location to write your content (before that, make sure you have appropriate rights):
File entityFile = new File(getServletContext().getContextPath() + "entities.txt");
FileWriter fOut = new FileWriter(entityFile);
fOut.write("The Content");
fOut.close();
Or if you want the directory also, you'll have to execute some additional steps, create it first then specify the file name inside it where you want to write:
File entityFolder = new File(getServletContext().getContextPath() + "EntitiesList");
entityFolder.mkdir();
File entityFile = new File(entityFolder, "entities.txt");
FileWriter fOut = new FileWriter(entityFile);
fOut.write("The Content");
fOut.close();
First there is Typo error in your path
Second you should use getResourceAsStream() for loading file for writing.
Code example:
InputStream input = getServletContext().
getResourceAsStream("/WEB-INF/EntityList/entities.txt");
Files.copy(InputStream input , Path target)
//Or Files.copy(Path source, OutputStream out)
It seem easier to use FileInputStream, but it is better to use ResourceStream.
Read here https://stackoverflow.com/a/2161583/8307755
https://stackoverflow.com/a/2308224/8307755

How to get the path of a file inside a project to read it with OpenCSV

I have a CSV file inside a folder that's inside the source folder but I can't get to it.
I got it to work with what I've found on internet:
URL url = getClass().getResource("/csv/recetas.csv");
File file = new File(url.getPath());
FileReader fileReader = new FileReader(file);
CSVReader csvReader = new CSVReader(fileReader, ',', '"', 1);
but it only works when I run it in the IDE. When I build the jar and try to run it, the FileReader can't find the file, it doesn't throw error for URL or File.
Here is my project folder so you can understand me. Thanks.
InputStream in = getClass().getResourceAsStream("/csv/recetas.csv");
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
CSVReader(reader, ',', '"', 1);
Resources are class path "files" possibly packed in a jar. They are not File, and are read-only.
Also for compatibility, give the charset explicitly.
The getClass().getResource() uses the class loader to load the resource. This means that your csv file will not be visible unless it is in the classpath.
Looking at your code and your problem again, getClass().getResource() seems redundant to me as the constructor of File(...) accepts a file path depicted as String.
See:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html
Quote:
File(String pathname) Creates a new File instance by converting the
given pathname string into an abstract pathname.
To make your program more versatile I would recommend you to avoid hardcoding the file path as the csv file can be anywhere within the file system and it may not always be called recetas.csv.
What people typically would do is to make the java program accept an option like --csv. Then let the user specify the filepath and your code will just be new File(theSpecifiedPath).

Getting the path of a txt file in a src folder so i can read from it into an array

I have a text file, that I am trying to convert to a String array (where each line is an element of the array).
I have found a code here that seems to do this perfectly, the only problem is, even when I use the relative path of the file, I get a FileNotFoundException.
The relative file path:
String path = "android.resource://"+getPackageName()+"/app/src/main/res/raw/"
+ getResources().getResourceEntryName(R.raw.txtAnswers);
When I try to use this path in a reader
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(path));
......
The path is underlined in red and says FileNotFoundException.
Perhaps it is expecting another type of path (not relative?) or did I get the path wrong?
The relative file path
That is not a file path.
Perhaps it is expecting another type of path
res/raw/... is a file on your hard drive. It is not a file on the device.
To access raw resources, use getResources() (called on any Context, like an Activity or Service) to get a Resources object. Then, call openRawResource(), passing in your resource ID, to get an InputStream on that resource's contents.
According to me the best way would be to past that txt file in assets folder of your source code.
To use that File just use the following snippet:
InputStream inputStream = getAssets().open("YOUR_TEXT_FILE");
It returns InputStream which further can be used to read the File & convert the data into a Array

How to move/rename uploaded file?

I followed this tutorial for uploading a file in my JSF2 application.
The application works fine but I am unhappy with one aspect.
While rebuilding the request, the File sent via request is saved somewhere on the disk.
Even though the file is saved I need to rename the file with a name which is available after entering the Managed Bean containing the action method.
Therefore I decided to create a new file with de desired name, copy the already saved file, and then delete the unneeded one.
private File uploadFile;
//...
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(newFile));
BufferedReader br = new BufferedReader(new FileReader(uploadFile));
String line = "";
while ((line = br.readLine()) != null){
bw.write(line);
}
} catch (Exception e){}
The new file appears in the desired location but this error is thrown when I'm trying to open the file: "Invalid or unsupported PNG file"
These are my questions:
Is there a better way to solve this problem?
Is this solution the best way to upload a picture? Is there a reason to save the file before the business logic when there may be need to resize the picture or the desired name is not available yet.
LE:
I know abot this tutorial as well but I'm trying to do this mojarra only.
There is a rename method built into java.io.File object already, I'd be surprised if it didn't work for your situation.
public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent:
The rename operation might not be able to move a file from one filesystem to
another, it might not be atomic, and it might not succeed if a file with the
destination abstract pathname already exists. The return value should always
be checked to make sure that the rename operation was successful.
You can also check if a file exists before saving it, and you can use the ImageIO class to do validations on the uploaded file before performing the initial save.
Don't use Reader and Writer when you deal with binary files like images. Use streams: FileInputStream and FileOutputStream. And the best variant is to use #Perception solution with renameTo method.
Readers read file as if it consists of characters (e.g. txt, properties, yaml files). Image files are not characters, they are binary and you must use streams for that.

Categories

Resources