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.
Related
response =
File("src\\test\\java\\com\\resources\\products\\response.json").bufferedReader()
.use { it.readText() }
I have this line of code for mocking response and it is working fine on pc but throws not found on macbook? Any solutions? Thanks.
You can create assets directory in unit test dir(java unit test), and put your response.json into it. and then you can read this file with these code below:
private static File readAssetsFile(String fileName) {
// create file for assets file
final String dir = System.getProperty("user.dir");
File assetsDir = new File(dir, File.separator + "src/test/assets/");
return new File(assetsDir, fileName);
}
private static String streamToString(InputStream inputStream)
throws IOException {
if (inputStream == null) {
return "";
}
StringBuilder sBuilder = new StringBuilder();
String line;
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
sBuilder.append(line).append("\n");
}
return sBuilder.toString();
}
// YOUR TESTCASE
#Test
public void testReadResponseJson() throws IOException {
File respFile = readAssetsFile("response.json");
String respText = streamToString(new FileInputStream(respFile));
assertEquals("{}", respText);
}
I have solved with:
val home = System.getProperty("user.home")
val file = File(home + File.separator + "Desktop" + File.separator + "response.json")
Desktop directory for the sample. I will give the absolute path step by step.
I want to access the certificate file what should be the path if that file is in resources/certs/ folder.
I tried it with the classpath put still getting the exception FileNotFound.
what should be path for that I should specify for this in my application.properties.
if you want to read a file, you can use this code (fileName: "/certs/xxx")
public String readFile(String fileName) throws IOException {
InputStream inputStream = this.getClass().getResourceAsStream(fileName);
StringBuilder resultStringBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
}
return resultStringBuilder.toString();
}
Today, I read the Basic I/O in the Java tutorial and I find some problem:
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("/workspaces/test/a.txt");
outputStream = new FileWriter("/workspaces/test/b.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
But when I run the demo, it failed. In the Console:
Exception in thread "main" java.io.FileNotFoundException: /workspaces/test/b.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at java.io.FileWriter.<init>(FileWriter.java:63)
at Demo.CopyCharacters.main(CopyCharacters.java:13)
How can I do that?
File might have a lock and forbid you to open it for writing (i.e. your application is still on a break point in debug mode and you forgot to stop it or you killed the app and the process is still running in memory). You can check by doing this:
inputStream = new FileReader("/workspaces/test/a.txt");
File outFile = new File("/workspaces/test/b.txt");
if (!outFile.canWrite()) {
System.err.println("Cannot write into file: " + outFile.getAbsolutePath());
}
outputStream = new FileWriter(outFile);
You can also renname your out file "b.txt" for something else and it will work as before (until you locked it again by accident). An other way to do this is to use a temporary file:
public static void main(String[] args) throws Exception {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("/workspaces/test/a.txt");
File file = File.createTempFile("test", null);
outputStream = new FileWriter(file);
System.out.println(file.getAbsolutePath());
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
Good for coding (and debugging). It ensures that it will be deleted by the OS after.
Maybe you should try to use a new feature that takes care of your resources automatically by putting them inside the try-catch block?
public static void main(String[] args) throws IOException {
try (
FileReader inputStream = new FileReader("/workspaces/test/a.txt");
FileWriter outputStream = new FileWriter("/workspaces/test/b.txt");
)
{
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
}
}
If you write your code in this manner, you don't need the finally block, because java will take care of the resources that are inside the try block brackets.
I some code that takes a file called wonder1.txt and writes the date in that file to another file. Lets say I have more files like wonder2.txt, wonder3.txt, wonder4.txt. How do I write the rest in the same file.
import java.io.*;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/Alice/new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you have list of files, then you can loop over them one by one. Your current code moves inside the loop.
The easier way would be to put all the files in one folder and read from it.
Something like this :
File folder = new File("/Users/DAndre/Desktop/Alice");
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
I am writing a small file upload utility thing as part of a larger project. Originally I was handling this from a servlet using the Apache commons File utility classes. Here is a snippet from a quick test client I wrote for the service:
public static void main(String[] args) {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
factory.setServiceClass(FileUploadService.class);
factory.setAddress("http://localhost:8080/FileUploadService/FileUploadService");
FileUploadService client = (FileUploadService) factory.create();
FileType file = new FileType();
file.setName("statemo_1256144312279");
file.setType("xls");
DataSource source = new FileDataSource(new File("c:/development/statemo_1256144312279.xls"));
file.setHandler(new DataHandler(source));
Boolean ret = client.uploadFile(file);
System.out.println (ret);
System.exit(0);
}
This works absolutely fine. Now the problem comes when I am trying to replace the Apache commons utilities. In the above code I am creating a DataSource from a File with an absolute path name. In my servlet, I can't get an absolute path name however and the file I am sending over the wire is empty.
Here is the servlet code:
#SuppressWarnings("unchecked")
protected void doPost (final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
// form should have enctype="multipart/form-data" as an attribute
if (!ServletFileUpload.isMultipartContent (request)) {
LOG.info("Invalid form attribute");
return;
}
//DataInputStream in = new DataInputStream(request.getInputStream());
final DiskFileItemFactory factory = new DiskFileItemFactory ();
factory.setSizeThreshold(FILE_THRESHOLD_SIZE);
final ServletFileUpload sfu = new ServletFileUpload (factory);
sfu.setSizeMax(MAX_FILE_SIZE);
final HttpSession session = request.getSession();
final List<FileItem> files = new ArrayList<FileItem>();
final List<String> filesToProcess = new ArrayList<String>();
try {
final List<FileItem> items = sfu.parseRequest(request);
for (final FileItem f : items) {
if (!f.isFormField())
files.add(f);
}
/*for (final FileItem f : files) {
final String absoluteFileName = UPLOAD_DESTINATION + FilenameUtils.getName(f.getName());
//f.write(new File (absoluteFileName));
filesToProcess.add(absoluteFileName);
}*/
FileItem f = files.get(0);
LOG.info("File: " + FilenameUtils.getName(f.getName()));
LOG.info("FileBaseName: " + FilenameUtils.getBaseName(f.getName()));
LOG.info("FileExtension: " + FilenameUtils.getExtension(f.getName()));
FileUploadServiceClient client = new FileUploadServiceClient();
DataSource source = new FileDataSource(new File(f.getName()));
FileType file = new FileType();
file.setHandler(new DataHandler(source));
file.setName(FilenameUtils.getBaseName(f.getName()));
file.setType(FilenameUtils.getExtension(f.getName()));
Boolean ret = client.uploadFile(file);
LOG.info("File uploaded - " + ret);
filesToProcess.add(UPLOAD_DESTINATION + FilenameUtils.getName(f.getName()));
session.setAttribute("filesToProcess", filesToProcess);
final RequestDispatcher dispatcher = request.getRequestDispatcher("Validate");
if (null != dispatcher) {
dispatcher.forward(request, response);
}
} catch (FileUploadException e) {
LOG.info("Exception " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
LOG.info("Exception " + e.getMessage());
e.printStackTrace();
}
}
I've been working on this for the better part of this morning and am not getting anywhere. Even if I get rid of the Apache commons file stuff completely and handle the parsing of the request myself, I still can't construct the DataSource appropriately.
Thanks!
This was rather simple actually, I just copied over the bytes from the InputStream to the DataSource:
FileItem f = files.get(0);
// there is a problem here where the file being created is empty, since we only have a
// partial path:
DataSource source = new FileDataSource(new File(f.getName()));
// because of the above problem, we are going to copy over the data ourselves:
byte[] sourceBytes = f.get();
OutputStream sourceOS = source.getOutputStream();
sourceOS.write(sourceBytes);
This is the code of commons-email ByteArrayDataSource
it sounds odd to try to replace apache commons - don't, unless you have a really good reason
you can get absolute paths in a servlet. You can call getServletContext().getRealPath("/") which will return the absolute path of your application, and then you can get files relative to it.
In our application there are objects that have properties InputStream and Name. We are using next class to construct DataSource with those properties.
public class InputStreamDataSource implements DataSource {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
private final String name;
public InputStreamDataSource(InputStream inputStream, String name) {
this.name = name;
try {
int nRead;
byte[] data = new byte[16384];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
inputStream.close();
buffer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public String getContentType() {
return new MimetypesFileTypeMap().getContentType(name);
}
#Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(buffer.toByteArray());
}
#Override
public String getName() {
return name;
}
#Override
public OutputStream getOutputStream() throws IOException {
throw new IOException("Read-only data");
}
}
Most of the solutions shown here require that the InpustStream be closed (read into memory). It is possible to wrap the InputStream in a DataSource object without closing the InputStream though:
private record PipedDataSource(InputStream in, String contentType, String encoding)
implements DataSource, EncodingAware {
public String getContentType() {
return contentType;
}
public InputStream getInputStream() {
return in;
}
public String getName() {
return "PipedDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("No OutputStream");
}
#Override
public String getEncoding() {
return encoding;
}
}
The example above also implements EncodingAware. This can prevent the InputStream from being closed by third part libraries (for example java.mail.internet.MimeUtility) when they get the data source encoding.