I have to delete and rename the files in doPost.but while executing some of the files are deleting some othes are not. When the same code i run in java the operation is succesfully carried out.here is the code i used for deleating files inside a directory.The same below code is i used in servlet.
public static void updateRootFile(String directorypath, String appID, String[] appName) throws IOException {
try {
FileInputStream fin = null;
File[] listOfFiles=fileLists(directorypath);
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
rootFiles = listOfFiles[i].getName();
if (rootFiles.endsWith(".properties") || rootFiles.endsWith(".PROPERTIES")) {
fin = new FileInputStream(directorypath + rootFiles);
properties.load(new InputStreamReader(fin, Charset.forName("UTF-8")));
String getAppName = properties.getProperty("root.label." + appID);
String propertyStr = "root.label." + appID;
saveFile(fin, getAppName, directorypath + rootFiles, propertyStr, appName[i]);
}
}
}
} catch (Exception e) {
System.out.println("expn-" + e);
}
}
public static void saveFile(FileInputStream fins, String oldAppName, String filePath, String propertyStr, String appName)
throws IOException {
String oldChar = propertyStr + "=" + oldAppName;
String newChar = propertyStr + "=" + appName;
String strLine;
File f1 = new File(filePath);
File f2 = new File("C:\\Equinox\\RootSipResource\\root\\root_created.properties");
BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(f1), "UTF-8"));
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(f2), "UTF-8");
while ((strLine = br.readLine()) != null) {
strLine = strLine.replace(oldChar, newChar);
out.write(strLine);
out.write("\r\n");
}
out.flush();
out.close();
br.close();
fins.close();
}
Servlet code:
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import root.sip.RootSipResourceApp;
public class SendRedirect extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
String strDirectorypath = (String) request.getParameter("txtfileBrowse");
request.setAttribute("directorypath", strDirectorypath);
String strappID = request.getParameter("txtAppID");
String[] appNames = {strEn, strAr, strBg, strCs, strDa, strDe, strEl, strEs, strFi, strFr, strHe, strHr, strHu, strIt,strLw, strJa, strKo, strNl, strNo, strPl, strPt, strRo, strRu, strSk, strSl, strSv, strTr, strZh, strZh_TW };
RootSipResourceApp.updateRootFile(strDirectorypath, strappID, appNames);
System.out.println("after................");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
It could be that your static methods are being accessed by multiple Servlet Threads at once.
You can make the saveFile() and updateRootFile() synchronized to prevent being accesed by multiple threads.
Related
I have to write a program where the user selects a .java file and the program creates an html file and writes all of the code into it, adding the necessary HTML tags so it will display properly. No matter what I think of and find online I can't get anything to properly make this happen, the only thing that writes is those HTML tags that are in the string I created.
It runs, user can select the file and choose where to save it. The file itself gets created, but none of the information from the .java file gets into the .html file.
package convertjavahtml;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.filechooser.*;
import static jdk.nashorn.internal.runtime.ScriptingFunctions.readLine;
public class ConvertJavaHTML {
public static void main(String[] args) throws IOException{
String name = null;
String newname = null;
try {
FileNameExtensionFilter filter = new FileNameExtensionFilter("Java", "java");
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
name = file.getName();
newname = name.substring(0, name.indexOf("."));
}
FileNameExtensionFilter filter2 = new FileNameExtensionFilter("html files (*.html)", "html");
JFileChooser saver = new JFileChooser();
saver.setFileFilter(filter2);
saver.setSelectedFile(new File(newname));
int returnVal2;
returnVal2 = saver.showSaveDialog(null);
int response = 0;
if(returnVal2 == JFileChooser.APPROVE_OPTION)
{
FileWriter write = new FileWriter(saver.getSelectedFile()+".html");
write.close();
}
File file = new File(name);
Scanner scanner = new Scanner(file);
String beg = "<h2>Demo.java</h2>\n<html>\n<pre>\n<body>\n";
String end = "\n</body>\n</pre>\n</html>";
PrintWriter out = new PrintWriter(new File(newname + ".html"));
out.println(beg);
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(chooser.getName(file)))) {
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(newname), "utf-8"))) {
writer.write(readLine);
}
}
}
out.print(end);
out.flush();
out.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
private static char handleFile(File file, Charset encoding) throws IOException {
try
(InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in, encoding);
Reader buffer = new BufferedReader(reader)){
return handleChars(buffer);
}
}
private static char handleChars(Reader reader) throws IOException {
int r;
while((r = reader.read()) != -1)
{
char ch = (char) r;
System.out.println(ch + " ");
}
return 0;
}
}
I'm very new to JAVA. I tried to save image through Java servlet and Ajax in netbeans. In netbeans I tried same coding with tomcat server is working fine.If I use Glashfish it's throwing error. Below is my coding.
Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part img = request.getPart("img");
String id = (String) request.getParameter("ids");
out.println(saveImage(img, "E:\\Users\\XXXX\\Desktop\\wine_shop\\build\\web\\images\\wines"));
}
Save image method:
private String saveImage(Part img, String path) throws IOException {
File fileSaveDir = new File(path);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());
String fileName = null;
fileName = extractFileName(img);
img.write(path+ fileName);
return "1";
}
My Error:
java.io.FileNotFoundException: E:\Users\xxxx\AppData\Roaming\NetBeans\8.2\config\GF_4.1.1\domain1\generated\jsp\wine_shop\E:\Users\xxxx\Desktop\wine_shop\build\web\images\winesth.jpg (The filename, directory name, or volume label syntax is incorrect)
Help to fix this..
Try This Code..
#WebServlet(name = "abc", urlPatterns = {"/upload"})
#MultipartConfig
public class abc extends HttpServlet {
private final static Logger LOGGER =
Logger.getLogger(abc.class.getCanonicalName());
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
final String path = "E:\\shopping\\web\\admin\\img";
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, path});
} catch (FileNotFoundException fne) {
writer.println("<br/> ERROR: " + fne.getMessage());
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
As per the captioned subject, I am not able to delete String from a text file on deployment in tomcat. Although it works absolutely fine in netbeans or eclipse.
When application is deployed it always says 'could not delete file'. Also I am not able to manually delete the file as I get 'Cannot delete file: It is in use by some other programs'.
But I am able to append String to this same text file.
This is the code that I am using to delete String from the file.
package com.pro.model;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RemoveLine {
private String inputFileName = "D:\\Marquee\\Copy of Scroll.txt";
public boolean deleteData(String msg, int pos) throws IOException {
//List msg_remove = null;
System.out.println("msg :" + msg);
BufferedReader reader = null;
try {
File inputFile = new File(inputFileName);
File tempFile = new File("D:\\myTempFile.txt");
reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = msg;
String currentLine;
while ((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String[] trimmedLine = currentLine.split("\\|");
System.out.println("currentLine :" + currentLine);
System.out.println("trimmedLine :" + trimmedLine.length);
for (int i = 0; i < trimmedLine.length; i++) {
int k = i + 1;
System.out.println("Calculating the size of field " + k);
//writer.write("Column " + k + " is " + trimmedLine[i].length());
// is.flush();
// is.newLine();
System.out.println("trimmedLine[i] :" + trimmedLine[i]);
//writer.write(trimmedLine[i] + "|");
System.out.println("trimmedLine[i].equals(lineToRemove) :" + trimmedLine[i].equals(lineToRemove));
//if (trimmedLine[i].equals(lineToRemove)) {
if (i == pos) {
System.out.println("trimmedLine in if:" + trimmedLine[i]);
//writer.flush();
//trimmedLine.replaceAll(currentLine, "");
continue;
}
System.out.println("currentLine :" + currentLine);
//writer.write(currentLine + "|");
writer.write(trimmedLine[i] + "|");
}
}
writer.flush();
reader.close();
writer.close();
if (!inputFile.delete()) {
System.out.println("Could not delete file");
return false;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inputFile)) {
System.out.println("Could not rename file");
return false;
}
return true;
//boolean successful = tempFile.renameTo(inputFile);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
return false;
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public List readText() throws FileNotFoundException, IOException {
BufferedReader reader = null;
List msg_after_removed = new ArrayList();
try {
File inputFile = new File(inputFileName);
//File tempFile = new File("C:\\myTempFile.txt");
reader = new BufferedReader(new FileReader(inputFile));
//msg_after_removed = new ArrayList();
if (inputFile.exists()) {
//data = msg1;
FileWriter fileWritter = new FileWriter(inputFile.getPath(), true);
System.out.println("file.getName():" + inputFile.getName());
System.out.println("file.getName():" + inputFile.getPath());
reader = new BufferedReader(new FileReader(inputFile));
String currentLine;
while ((currentLine = reader.readLine()) != null) {
String[] trimmedLine = currentLine.split("\\|");
for (int i = 0; i < trimmedLine.length; i++) {
Bean getdata = new Bean();
System.out.println("trimmedLine in read ==" + trimmedLine[i] + i + "=length=" + trimmedLine.length);
getdata.setMsg(trimmedLine[i]);
String arr[] = trimmedLine[i].split(":");
System.out.println("arr[] in read" + arr[1]);
getdata.setDate(arr[0]);
getdata.setMsg(arr[1]);
msg_after_removed.add(getdata);
//reader.close();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
Bean getdata = new Bean();
getdata.setDate("0");
getdata.setMsg("0");
msg_after_removed.add(getdata);
System.out.println("in catch");
//reader.close();
//return false;
} finally {
if (reader != null) {
reader.close();
}
}
return msg_after_removed;
}
}
I thought maybe Read stream is not closing properly & that is why I am not able to delete/save file manually. But if that was the case, I should also not be able to append String to the file.
Any help is appreciated.
I run my java webserver on port 6799
My directory has a txt.txt file and pdf.pdf file
When I give localhost:6799/txt.txt, it gives perfect output saying
GET /txt.txt HTTP/1.1HTTP/1.0 200 OK
Content-type: text/plain
This is a very simple text file
But when I give localhost:6799/pdf.pdf from browser, it gives java.lang.NullPointerException
This is my code
import java.net.*;
public final class WebServer {
public static void main(String args[]) throws Exception {
int port = 6799;
System.out.println("\nListening on port " + port);
ServerSocket listen = new ServerSocket(port);
while (true) {
Socket socket = listen.accept();
HttpRequest request = new HttpRequest(socket);
Thread thread = new Thread(request);
thread.start();
}
}
}
--
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
public final class HttpRequest implements Runnable {
final String CRLF = "\r\n";
Socket socket;
public HttpRequest(Socket socket) throws Exception {
this.socket = socket;
}
#Override
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
BufferedReader br;
DataOutputStream dos;
try (InputStream is = socket.getInputStream()) {
br = new BufferedReader(new InputStreamReader(is));
String requestline = br.readLine();
System.out.println("\n" + requestline);
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
dos = new DataOutputStream(socket.getOutputStream());
dos.writeBytes(requestline);
StringTokenizer tokens = new StringTokenizer(requestline);
tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory.
fileName = "." + fileName;
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "HTTP/1.0 200 OK" + CRLF;
contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
} else {
statusLine = "HTTP/1.0 404 Not Found" + CRLF;
//contentTypeLine = "Content-type: " + "text/html" + CRLF;
entityBody = "<HTML>"
+ "<HEAD><TITLE>Not Found</TITLE></HEAD>"
+ "<BODY>Not Found</BODY></HTML>";
}
dos.writeBytes(statusLine);
dos.writeBytes(contentTypeLine);
dos.writeBytes(CRLF);
if (fileExists) {
sendBytes(fis, dos);
fis.close();
} else {
dos.writeBytes(entityBody);
}
}
br.close();
dos.close();
socket.close();
}
private void sendBytes(FileInputStream fis, DataOutputStream dos) throws IOException {
byte[] buffer = new byte[4096];
int bytes = 0;
while ((bytes = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytes);
}
}
private String contentType(String fileName) {
if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
return "image/jpeg";
}
if (fileName.endsWith(".gif")) {
return "image/gif";
}
if (fileName.endsWith(".txt")) {
return "text/plain";
}
if (fileName.endsWith(".pdf")) {
return "application/pdf";
}
return "application/octet-stream";
}
}
STACK TRACE
java.lang.NullPointerException
at java.io.DataOutputStream.writeBytes(DataOutputStream.java:274)
at HttpRequest.processRequest(HttpRequest.java:65)
at HttpRequest.run(HttpRequest.java:20)
at java.lang.Thread.run(Thread.java:724)
At least one issue is this code:
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
BufferedReader will return null at the end of the stream, so calling .length() on a null object will yield a NullPointerException.
A more idiomatic way to write this is:
while ((headerLine = br.readLine()) != null && headerLine.length() != 0) {
System.out.println(headerLine);
}
...which takes advantage of short-circuit logic to not evaluate the second condition if the result of (headerLine = br.readLine()) is null.
It is happening because for some reason you have toggled comment on the following line:
//contentTypeLine = "Content-type: " + "text/html" + CRLF;
Untoggle it and you're good!
I have to read a file using servlet.here is the code iam using.but file is not reading using this code.Always printing File contains null value-----------------:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("text/html");
String filename = "D/root.properties";
ServletContext context = getServletContext();
InputStream inp = context.getResourceAsStream(filename);
if (inp != null) {
InputStreamReader isr = new InputStreamReader(inp);
BufferedReader reader = new BufferedReader(isr);
PrintWriter pw = response.getWriter();
String text = "";
while ((text = reader.readLine()) != null) {
}
} else {
System.out.println("File contains null value-----------------");
}
} catch(Exception e) {
System.out.println("Rxpn............................................."+e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
javadoc to the rescue :
java.net.URL getResource(java.lang.String path)
throws java.net.MalformedURLException
Returns a URL to the resource that is mapped to the given path.
The path must begin with a / and is interpreted as relative to the current context root, or relative to the /META-INF/resources directory
of a JAR file inside the web application's /WEB-INF/lib directory.
This method will first search the document root of the web application
for the requested resource, before searching any of the JAR files
inside /WEB-INF/lib. The order in which the JAR files inside
/WEB-INF/lib are searched is undefined.
If you want to read from a resource in the web app, use a path as indicated above. If you want to read from the file system, use file IO (and the correct file name): new FileInputStream("D:/root.properties")
Use following code.
With this you can read file
File file = new File("Filepath");
try {
if (file.exists()) {
BufferedReader objBufferReader = new BufferedReader(
new FileReader(file));
ArrayList<String> arrListString = new ArrayList<String>();
String sLine = "";
int iCount = 0;
while ((sLine = objBufferReader.readLine()) != null) {
arrListString.add(sLine);
}
objBufferReader.close();
for (iCount = 0; iCount < arrListString.size(); iCount++) {
if (iCount == 0) {
createTable(arrListString.get(iCount).trim());
} else {
insertIntoTable(arrListString.get(iCount).trim());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream file = new FileInputStream("c:\\hi.txt");
DataInputStream input = new DataInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String text = "";
while ((text = br.readLine()) != null) {
System.out.println(text);
}
}
}
Please try the above code sample. I think in your code , file is not found. Please give the file path in the above code and try.