I have a client-server model, wherein the client is filling a form, and the server saves the form data into a .csv file. Here is the code I'm using to write to the csv:
String fileName="responses.csv";
File f = new File(fileName);
PrintWriter toFile = new PrintWriter(new BufferedWriter(new FileWriter(f, true)));
toFile.println("test1,test2,\"test3,test4\"");//test code
toFile.close();
I have a Java Servlet (javax.servlet-API 3.1.0) and a Tester.java class in a package. Tester.java has a main() method in it, which executes the above code and then terminates.
When I run this code in the Tester, it works fine and the csv is written as expected.
However, in my Servlet, the file is not written. I do not see any Exception to indicate that I have an access issue. Since both .java files are in the same package, they can both access my csv file.
Note that my main() method terminates after file writing whereas my Servlet does not.
Why is my servlet not able to write to file ? Any guidance is earnestly appreciated. Thanks
Please check if the file created actually exists and what permissions you see. Try to save the csv file on a path where the user has write permission.
Also, if there is no error, print the absolute path for the file to see where it got written to.
Related
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
Can anyone help me how to change a line in a file using java IO function. The file is located at SDCard. I have tried some solution from different blog, but failed.
I need to change one attribute wpa_oper_channel=1 to 2,3,4..... as user demand in the file sdcard/sample.txt.
I have also tried using SED command, but still not working. Please suggest if there any solution using java IO function.
The Command I have used using SED :
sed -i 's/wpa_oper_channel=[0-9]\\+/wpa_oper_channel=7/' sample.txt
If your configuration file is in the form of a Properties file. This means each line is in a format of key=value. You can easily read, modify and write it. Here is an example, I assume you have no problem with reading and writing a file through streams.
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"sample.txt");
InputStream is = new FileInputStream(file); // Read your existing file
Properties props = new Properties();
props.load(is);
props.setProperty("wpa_oper_channel", "4");
OutputStream out = new FileOutputStream(file); // Your output file stream
prop.store(output, null); // Save your properties file without header
By doing this, you may lose if there is another type of line like comments or else.
Update
I updated to source code. But still you need to get read and write permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I haven't test the code, It will work with some exception handling. If it is not work please specify your error.
You just have to
read the file's content into memory (there are millions of examples on how to do that with java),
change the content (finding the position could be done using e.g. indexOf("wpa_oper_channel="))
write the content back to the file (there are millions of examples for that too)
What android do you use?
From android 4.4+ user haven't access to edit and remove files from SD Card. You must copy them to external storage and use there. See this link - http://code.google.com/p/android/issues/detail?id=67570
I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.
Could you help to comment what is the equivalent in Java for the following fmShareDenyNone FileOpen statement in Delphi?
TFileStream.Create(
'C:\Test.txt', fmOpenRead or fmShareDenyNone);
, where fmShareDenyNone is used in the FileOpen call together with one of fmOpenReadWrite, fmOpenRead or fmOpenWrite, to open a file so other processes can read/write the file as well.
Currently I am using the following statement to Open a file for Write. It gives "java.nio.file.FileSystemException: ... the file because it is being used by another process." if I opened a second file viewer such as UltraEdit.
BufferedWriter br = java.nio.file.Files.newBufferedWriter(
java.nio.file.Paths.get("test.txt"),
java.nio.charset.Charset.forName("UTF-8"),
new java.nio.file.OpenOption[]{java.nio.file.StandardOpenOption.WRITE}
);
PS: I am hoping a built-in equivalent(which is naturally cross-platform).
Many thanks for your opinions!
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.