issue with having java in a tomcat servlet edit a .txt file - java

Hey guys I am trying to have my code, once run through; it will insert into a .txt document that is already made, in the WebContent directory. I am running in Apache Tomcat v7.0 - building in Eclispe.
CODE:
public static void insertWinner(String winner) throws IOException{
String filename= "Winner.txt";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("Winner is" + winner);//appends the string to the file
fw.close();
}
This is being done inside a java file called BandIO which the servlet BandListServ.java calls on to insert a string value into the above code.
Nothing happen when I do this, not to sure why either.
Let me know if you need anyother info, Thanks again!
EDIT
I change it to this -
public static void insertWinner(String winner) throws IOException{
FileWriter out = new FileWriter("Winner.txt");
out.write("Hello");
out.close();
out = new FileWriter("Winner.txt", true);
out.write(", world!");
out.close();
}
EDIT:
Okay so I tried this inside the servlet file but no cigar..
response.setContentType("text/html");
String filename = "Winner.txt";
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream(filename);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
PrintWriter writer = response.getWriter();
String text = "Winner is";
while ((text = reader.readLine()) != null) {
writer.println(text);
}
}

In principle access to the file system is done with
File file = getServletContext().getRealPath("/Winner.txt");
This file could be null, namely when the web application is deployed as .war (so zip format), and the web server is not configured to unpack the war.
In your case a file could have a concurrency problem, needing some locking. Maybe you should use a database table.
Also on next deployment the file might get lost.

Related

How to create and output to files in Java

My current problems lie with the fact that no matter what solution I attempt at creating a file in Java, the file never, ever is created or shows up.
I've searched StackOverflow for solutions and tried many, many different pieces of code all to no avail. I've tried using BufferedWriter, PrintWriter, FileWriter, wrapped in try and catch and thrown IOExceptions, and none of it seems to be working. For every field that requires a path, I've tried both the name of the file alone and the name of the file in a path. Nothing works.
//I've tried so much I don't know what to show. Here is what remains in my method:
FileWriter fw = new FileWriter("testFile.txt", false);
PrintWriter output = new PrintWriter(fw);
fw.write("Hello");
I don't get any errors thrown whenever I've run my past code, however, the files never actually show up. How can I fix this?
Thank you in advance!
There are several ways to do this:
Write with BufferedWriter:
public void writeWithBufferedWriter()
throws IOException {
String str = "Hello";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();
}
If you want to append to a file:
public void appendUsingBufferedWritter()
throws IOException {
String str = "World";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(str);
writer.close();
}
Using PrintWriter:
public void usingPrintWriteru()
throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Using FileOutputStream:
public void usingFileOutputStream()
throws IOException {
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Note:
If you try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown.
It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it.
In output stream, the close() method calls flush() before releasing the resources which forces any buffered bytes to be written to the stream.
Source and More Examples: https://www.baeldung.com/java-write-to-file
Hope this helps. Good luck.
A couple of things worth trying:
1) In case you haven't (it's not in the code you've shown) make sure you close the file after you're done with it
2) Use a File instead of a String. This will let you double check where the file is being created
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
FileWriter fw = new FileWriter(file, false);
fw.write("Hello");
fw.close();
As a bonus, Java's try-with-resource will automatically close the resource when it's done, you might want to try
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
try (FileWriter fw = new FileWriter(file, false)) {
fw.write("Hello");
}

Cannot find file in netbeans + glassfish project

Here it is my folder project
I would like to read the file book-form.html which is in the directory web of my project and put it in a String.
This is how I call my function 'getFileContent':
String content = getFileContent("web/book-form.html");
And this is the function:
public String getFileContent(String filePath){
String line, content = new String();
try {
File file = new File(filePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
content += line;
}
br.close();
fr.close();
} catch(IOException e){
System.out.println(e.getMessage());
}
return content;
}
My problem is that netbeans tell me that it cannot find my file book-form.html
Any ideas ?
File path to resource in our war/WEB-INF folder?
Also you should close stream in a final block or use try-with-resource if you use jdk 7+
I find the way to do it:
Basically the program is in the main folder of Glassfish, so it's needed to put the entire path of your file from the root of your system to allow the program to find your file.

BuferredReader problems

I am having trouble reading from a file. Here is my code can anyone show me where I am wrong?
public static Map<Route, List<Service>> read(String fileName)
throws IOException, FormatException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String strLine;
while((strLine = reader.readLine())!= null)
{
/* Own Code */
}
reader.close();
}
I am having a FileNotFound Exception. May this be a the location of my file that is wrong?
You seem to want to use a resource. A resource is not accessed as a file, it is better to use it as a stream.
InputStream resourceStream = MyClass.class.getResourceAsStream(fileName);
BufferedReader myReader = new BufferedReader(new InputStreamReader(resourceStream));
Above code takes the location of your class in account, so you can simply use the fileName as is, without a path, and place the fileName next to your .java file. It will automatically be placed next to the generated .class files and - when packaged - in your .jar file.
Just as owlstead commented keep in appropriate location and try like this
URL url = ClassLoader.getSystemResource(fileName);
br = new BufferedReader(new InputStreamReader(url.openStream()));
i.e keep the file in classes folder or bundle with jar or current working directory etc.

Having problems with removing first line from txt file

I know this is very basic stuff but for some reason I'm having problems with a bufferedReader/ Writer. I am trying to get the first line of text and return it to another method. However, for some reason the writer doesn't seem to be writing to the temp file and it isn't changing the name of the temp file either.
By throwing a few print statements I have been able to figure out:
The while loop is operating correctly
The if else statement is operating correctly
The tempFile is not writing to a text file correctly
The tempFile is not renaming correctly
There are no errors being thrown
private static String wavFinder() throws IOException{
String currentWav=null;
int x = 1;
File inputFile = new File("C:\\convoLists/unTranscribed.txt");
File tempFile = new File("C:\\convoLists/unTranscribedtemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine = null;
while((currentLine = reader.readLine()) != null) {
if(x == 1){
currentWav = currentLine;
}
else{
writer.write(currentLine);
}
x = 2;
}
boolean successful = tempFile.renameTo(inputFile);
System.out.println("Success: " + successful);
System.out.println("currentWav = " + currentWav);
return currentWav;
}
Here is the method I am using. If you notice anything please let me know and if you have any questions I will be sure to answer them quickly. Thank you :)
First flush the steam(writer) and close them.
You can not have two files with same name. You are trying to rename the temp file with input file. You need to delete input file and then rename it to that.
reader.close();
writer.flush();
writer.close();
inputFile.delete();
Add these lines before rename and it will work
Close your buffers before trying to call renameTo.
reader.close()
writer.close()
File inputFile = new File("C:\convoLists/unTranscribed.txt");
File tempFile = new File("C:\convoLists/unTranscribedtemp.txt");
Why you have different signs for path?
Always should be //.

Java project can't find file

I have a project that finds a text file and makes it into an array of characters. However, for some reason or another it isn't finding the file. This is all the code involving opening/reading the file:
public void initialize(){
try{
File file = new File(getClass().getResource("/worlds/world1.txt").toString());
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
for(int i = 0; (c = reader.read()) != -1; i ++) {
for(int x = 0; x < 20; x++){
worlds[1][x][i] = (char) c;
c = reader.read();
}
}
}catch(IOException e){
e.printStackTrace();
}
}
When ran, it shows in the console that it is pointing to the correct file, but claims nothing exists there. I've checked, and the file is completely intact and in existence. What could be going wrong here?
You should not get a resource like that. You can use
BufferedReader reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream("/worlds/world1.txt")
));
Also, be careful when you package your application if you develop it inside an IDE, otherwise you'll run into common CLASSPATH troubles
File path for embedded resources is calculated from the package root folder. Assuming that src folder is the root package folder, make sure, that world1.txt file is located at src/worlds/ folder and full path is src/worlds/world1.txt
Second point, use the following code to obtain embedded file reader object:
// we do not need this line anymore
// File file = new File(getClass().getResource("/worlds/world1.txt").toString());
// use this approach
BufferedReader reader = new BufferedReader(
new InputStreamReader(
getClass().getResourceAsStream("/worlds/world1.txt"),
Charset.forName("UTF-8")));
You haven't indicated where your file lives.
getClass().getResource is used to locate a resource/file on your classpath; the resource may be packaged in your jar, for example. In this case, you can't open it as a File; see Raffaele's response.
If you want to locate the resource/file on the file system, then create the File object directly without getResource():
new File("/worlds/world1.txt")
I was using Netbeans and I was getting similar results. When I defined the file Path from the C drive and ran my code it stated: Access has been denied.
The following code ran fine, just back track your file location to the source (src) file.
//EXAMPLE FILE PATH
String filePath = "src\\solitaire\\key.data";
try {
BufferedReader lineReader = new BufferedReader(new FileReader(filePath));
String lineText = null;
while ((lineText = lineReader.readLine()) != null) {
hand.add(lineText);
System.out.println(lineText); // Test print of the lines
}
lineReader.close(); // Closes the bufferReader
System.out.print(hand); // Test print of the Array list
} catch(IOException ex) {
System.out.println(ex);
}

Categories

Resources