InputStream is null - java

In a program I'm working on I have
String cwd;
String file_separator;
public ConfigLoader()
{
cwd = get_cwd();
file_separator = get_file_separator();
try
{
Properties c = new Properties();
InputStream in = this.getClass().getClassLoader().getResourceAsStream(cwd +
file_separator + "data" + file_separator + "configuration.properties");
c.load(in);
}
except (Exception e) { e.printStackTrace(); }
}
public String get_file_separator()
{
File f = new File("");
return f.separator;
}
public String get_cwd()
{
File cwd = new File("");
return cwd.getAbsolutePath();
}
For some reason, though, c.load(in); causes a NullPointerException. The exception comes from in == NULL being true. I can't figure out why because
System.out.println(cwd + file_separator + "data" + file_separator +
"configuration.properties");
prints
/users/labnet/st10/jjb127/workspace/Brewer-Client/data/configuration.properties
which is the location of the file I'm wanting to use.
Thoughts?

getResourceAsStream is meant to search for files on the classpath and not for accessing the local file system. You will have to use FileInputStream for this case.
InputStream in = new FileInputStream(cwd +
file_separator + "data" + file_separator + "configuration.properties");

Related

File.createTempFile in Java getting Incompatible type error

Till now my code works fine where I am creating file in temporary directory and processing it.
But now I am trying to provide specific directory where I actually want to create xml file. So in method createTmpXmlFile
private static Path createTmpXmlFile(final String prefix) {
try {
log.info("Creating temporary file {}{}", prefix, XML_SUFFIX);
return Files.createTempFile(Paths.get(gleifZipFile), prefix, XML_SUFFIX);
} catch (IOException e) {
throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
}
}
I changed from
return Files.createTempFile(prefix, XML_SUFFIX);
to
return File.createTempFile(prefix, XML_SUFFIX, "/tmp/in");
and I get following error:
java: incompatible types: java.lang.String cannot be converted to java.io.File.
If I change the logic here then its affecting other method that are calling createTmpXmlFile method.
I really don't understand how to resolve this issue. Below is my code:
#Slf4j
public class InputCS implements Runnable {
public static final String XML_SUFFIX = ".xml";
#Value("${gleifdataimporter.file.dir}")
private String gleifZipFile;
private void processleifZipFile() {
final AtomicBoolean isInsideLeiRecord = new AtomicBoolean();
isInsideLeiRecord.set(false);
final StringBuilder currentLeiRecordXml = new StringBuilder();
try (FileSystem zipFs = FileSystems.newFileSystem(jobRunner.getInputZipPath(), null)) {
Path tmpXMLPath = xmlFileFromLeiZipFile(zipFs);
try (Stream<String> lines = Files.lines(tmpXMLPath)) {
AtomicInteger processedLinesCounter = new AtomicInteger();
AtomicInteger currentLineNumber = new AtomicInteger();
lines.sequential().forEach(handleLineAndIncrementLineNumber(isInsideLeiRecord, currentLeiRecordXml, processedLinesCounter, currentLineNumber));
log.info("{} lines of XML file inside LEIF input ZIP file {} processed.", processedLinesCounter.get(), jobRunner.getInputZipPath());
}catch (IOException e) {
throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
} finally {
Files.delete(tmpXMLPath);
}
} catch (IOException e) {
throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
}
}
private Path xmlFileFromLeiZipFile(FileSystem zipFs) { //extracts the xml file from zip file
log.info("Input file {} exists: {}", jobRunner.getInputZipPath(), Files.exists(jobRunner.getInputZipPath()));
Path tmpXmlPath = createTmpXmlFile("leif__" + System.currentTimeMillis());
for (Path rootDir : zipFs.getRootDirectories()) {
try (Stream<Path> files = treeAt(rootDir)) {
log.info("Trying to extract LEIF XML file from ZIP file into {}.", tmpXmlPath);
final Path xmlFileInsideZip = files
.filter(isNotADir())
.filter(Files::isRegularFile)
.findFirst()
.orElseThrow(() -> new IllegalStateException("No file found in LEI ZIP file."));
log.info("Path to LEIF XML file inside ZIP file: {}.", xmlFileInsideZip);
return copyReplacing(xmlFileInsideZip, tmpXmlPath);
}
}
throw new IllegalStateException("No file found in LEI ZIP file " + jobRunner.getInputZipPath() + ".");
}
private static Path createTmpXmlFile(final String prefix) {
try {
log.info("Creating temporary file {}{}", prefix, XML_SUFFIX);
return Files.createTempFile(Paths.get(gleifZipFile), prefix, XML_SUFFIX);
} catch (IOException e) {
throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
}
}
#NotNull
private static Path copyReplacing(Path from, Path to) {
requireNonNull(from, "Trying to copy from a path, which is null to path " + to + "."); //trying to copy file where no xml file exist in root directory
requireNonNull(to, "Trying to copy from path " + from + " to a path, which is null.");
try {
return Files.copy(from, to, REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException("Cannot copy from " + from + " to " + to + ". ", e);
}
}
}
As suggested by Slaw, use Files#createTempFile(Path,String,String,FileAttribute...) to specify the directory to create temp file.
Use Paths#get(String,String...) for java 7 or 8, or Path#of(String,String...) for java 11 or later to convert String to Path. Further reading: Paths.get vs Path.of
private static Path createTmpXmlFile(final String prefix) {
try {
// Java 11 or later
// return Files.createTempFile(Path.of("/tmp/in"), prefix, XML_SUFFIX);
// Java 8
return Files.createTempFile(Paths.get("/tmp/in"), prefix, XML_SUFFIX);
} catch (IOException e) {
throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
}
}
File.createTempFile is expecting a File object as third parameter. Just wrap your "/tmp/in" into a File
=> return File.createTempFile(prefix, XML_SUFFIX, new File("/tmp/in")); and you should be good to go.
so you can do:
File.createTempFile("prefix", "suffix", new File("/tmp/in"));
Or using NIO (recommended)
Files.createTempFile(Paths.get("/tmp/in"), "prefix", "suffix");

java.lang.IllegalArgumentException: File Not found

I am trying to read an Ontology using Jena. I have a file Pizza.owl in the correct directory shown in the code, but I still get an error that the file is not found.
public static void ReadOntology(){
OntModel onto = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
String inputFileName = "C:\\Users\\najib\\studies\\pizza.owl";
try {
Logger logger = Logger.getLogger(Operations.class);
PropertyConfigurator.configure("C://Users//najib//Downloads//apache-jena-2.12.0//jena-log4j.properties");
//create the reasoning model using the base
OntModel model = ModelFactory.createOntologyModel();
// use the FileManager to find the input file
InputStream in = FileManager.get().open(inputFileName);
if (in == null) {
throw new IllegalArgumentException("File: " + inputFileName + " not found");
}
model.read(in, "");
//to list classes
ExtendedIterator<OntClass> classes = model.listClasses();
while (classes.hasNext()) {
OntClass cls = (OntClass) classes.next();
System.out.println("Classes: " + cls.getLocalName());
for (ExtendedIterator<OntClass> i = cls.listSubClasses(true); i.hasNext();) {
OntClass c = (OntClass) i.next();
System.out.print(" " + c.getLocalName() + "\n");
} // end for
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I get the following error: java.lang.IllegalArgumentException: File: C:\Users\najib\studies\pizza.owl not found
When I read the javadoc of FileManager, I see you have to prefix your file parameter with "file:"
So (without testing this answer) I suggest to try it with:
String inputFileName = "file:/C:/Users/najib/studies/pizza.owl";

How to upload file using java ?

Hello i m trying to upload file using java file.. but i don't get it.. i get file size=0 i'm providing here my java code. tell me why i cant upload on particular folder. i want to store my file in particular folder. i am trying to get file size, file name but i got the null value where am i wrong please tell me.
public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException
{
//image upload logic
String folder_for_upload =(getPortletContext().getRealPath("/"));
//String folder=actionRequest.getParameter("uploadfolder");
realPath=getPortletContext().getRealPath("/");
logger.info("RealPath is" + realPath);
logger.info("Folder is :" + folder_for_upload);
try
{
logger.info("Admin is try to upload");
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("fileName") == 0) {
SessionErrors.add(actionRequest, "error");
}
String sourceFileName = uploadRequest.getFileName("fileName");
File uploadedFile = uploadRequest.getFile("fileName");
System.out.println("Size of uploaded file: " + uploadRequest.getSize("fileName"));
logger.info("Uploded file name is: " + uploadRequest.getFileName("fileName"));
String destiFolder=("/home/ubuntu/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/imageUpload-portlet/image");
String newsourcefilename = (uploadRequest.getFileName("fileName"));
File newFile = new File(destiFolder +"/"+ newsourcefilename);
logger.info("New file name: " + newFile.getName());
logger.info("New file path: " + newFile.getPath());
InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(uploadedFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes_ = FileUtil.getBytes(in);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
Float size = (float) newFile.length();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);
logger.info("File created: " + newFile.getName());
SessionMessages.add(actionRequest, "success");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (NullPointerException e)
{
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}
}
You need to do this to upload small files < 1kb
File f2 = uploadRequest.getFile("fileupload", true);
They are stored in memory only. I have it in my catch statement incase I get a null pointer - or incase my original file (f1.length) == 0
I have executed your code.It is working as per expectation.There might be something wrong in your jsp page.I am not sure but might be your name attribute is not same as the one which you are using in processAction(assuming that you are using portlet).Parameter is case sensitive,so check it again.
You will find more on below link.It has good explanation in file upload.
http://www.codeyouneed.com/liferay-portlet-file-upload-tutorial/
I went through a file upload code, and when i implement that in my local system what i got is, portlet is saving the file i upload in tomcat/webbapp/abc_portlet_project location, what i dont understand is from where portlet found
String folder = getInitParameter("uploadFolder");
String realPath = getPortletContext().getRealPath("/");
System.out.println("RealPath" + realPath +"\\" + folder); try {
UploadPortletRequest uploadRequest =
PortalUtil.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));
if (uploadRequest.getSize("fileName")==0)
{SessionErrors.add(actionRequest, "error");}
String sourceFileName = uploadRequest.getFileName("fileName"); File
file = uploadRequest.getFile("fileName");
System.out.println("Nome file:" +
uploadRequest.getFileName("fileName")); File newFolder = null;
newFolder = new File(realPath +"\" + folder);
if(!newFolder.exists()){ newFolder.mkdir(); }
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("New file path: " + newfile.getPath());
InputStream in = new
BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(file); FileOutputStream fos
= new FileOutputStream(newfile);

Java delete and rename file issue

Method below has function to simply move files from the "working" to the "move" directory which paths it receives through the method call. It all works, but for the case when file name has name with two extensions (like .xml.md5) where the .renameTo method returns false. Is there a way to alter the below code so it would work regardless of the OS that it's run on. (Currently it is the Windows)
public void moveToDir(String workDir, String moveDir) throws Exception {
File tempFile = new File(workDir);
File[] filesInWorkingDir = tempFile.listFiles();
for (File file : filesInWorkingDir) {
System.out.println(file.getName());
if (new File(moveDir + File.separator + file.getName()).exists())
new File(moveDir + File.separator + file.getName()).delete();
System.out.println(moveDir + File.separator + file.getName());
Boolean renameSuccessful = file.renameTo(new File(moveDir + File.separator + file.getName()));
if (!renameSuccessful) throw new Exception("Can't move file to " + moveDir +": " + file.getPath());
}
}
I have simplified your code and added a check if delete was successful. Try it.
public void moveToDir(String workDir, String moveDir) {
for (File file : new File(workDir).listFiles()) {
System.out.println(file.getName());
final File toFile = new File(moveDir, file.getName());
if (toFile.exists() && !toFile.delete())
throw new RuntimeException("Cannot delete " + toFile);
System.out.println(toFile);
if (!file.renameTo(toFile))
throw new RuntimeException(
"Can't move file to " + moveDir +": " + file.getPath());
}
}

Java writing to a text file not working properly

The Java application that I support is logging some details in a flat file. the problem I face some times is that, the entry is very low compared to the previous day. This entry is most essential because our reports are generated based on the file. I went thro code for writing I couldn't figure out any issues. the method which is writing is sync method.
Any suggestions? I can also provide the code for you is you may need?
public synchronized void log (String connID, String hotline, String callerType,
String cli, String lastMenu, String lastInput,
String status, String reason)
{
//String absoluteFP = LOG_LOC + ls + this.getFilename();
//PrintWriter pw = this.getPrintWriter(absoluteFP, true, true);
try
{
pw.print (this.getDateTime ()+ ","+connID +","+hotline+","+callerType+","+ cli+"," + lastMenu + "," + lastInput + "," + status + "," + reason);
//end 1006
pw.print (ls);
pw.flush ();
//pw.close();
}
catch (Exception e)
{
e.printStackTrace ();
return;
}
}
private synchronized PrintWriter getPrintWriter (String absoluteFileName,
boolean append, boolean autoFlush)
{
try
{
//set absolute filepath
File folder = new File (absoluteFileName).getParentFile ();//2009-01-23
File f = new File (absoluteFileName);
if (!folder.exists ())//2009-01-23
{
//System.out.println ("Call Detailed Record folder NOT FOUND! Creating a new);
folder.mkdirs ();
//System.out.println ("Configure log folder");
this.setHiddenFile (LOG_LOC);//set tmp directory to hidden folder
if (!f.exists ())
{
//System.out.println ("Creating a new Call Detailed Record...");//2009-01-23
f.createNewFile ();//2009-01-23
}
}
else
{
if (!f.exists ())
{
//System.out.println ("Creating a new Call Detailed Record...");//2009-01-23
f.createNewFile ();//2009-01-23
}
}
FileOutputStream tempFOS = new FileOutputStream (absoluteFileName, append);
if (tempFOS != null)
{
return new PrintWriter (tempFOS, autoFlush);
}
else
{
return null;
}
}
catch (Exception ex)
{
ex.printStackTrace ();
return null;
}
}
/**
* Set the given absolute file path as a hidden file.
* #param absoluteFile String
*/
private void setHiddenFile (String absoluteFile)
{
//set hidden file
//2009-01-22, KC
Runtime rt = Runtime.getRuntime ();
absoluteFile = absoluteFile.substring (0, absoluteFile.length () - 1);//2009-01-23
try
{
System.out.println (rt.exec ("attrib +H " + "\"" + absoluteFile + "\"").getInputStream ().toString ());
}
catch (IOException e)
{
e.printStackTrace ();
}
}
private String getDateTime ()
{
//2011-076-09, KC-format up to milliseconds to prevent duplicate PK in CDR table.
//return DateUtils.now ("yyyy/MM/dd HH:mm:ss");
return DateUtils.now ("yyyy/MM/dd HH:mm:ss:SSS");
//end 0609
}
private String getFilename ()
{
///return "CDR_" + port + ".dat";//2010-10-01
return port + ".dat";//2010-10-01
}
public void closePW ()
{
if (pw != null)
{
pw.close ();
}
}
You've created a FileOutputStream, but aren't closing that stream. Close that stream and try again. That might be causing the problem.
Messages are getting logged sometime because the garbage collector kicks in at some intervals and closes the FileOutStream. This then allows messages to be logged again. You're getting the unreachable error since you have a return statement in both the if & else blocks. You'll have to take the PrintWriter and FileOutStreamWriter out of the getPrintWriter put it where you usually call the getPrintWriter(). Then you'll be able to close the streams correctly. getPrintWriter should only ensure file exists, so rename it to ensureFileExistance
If you can use Apache Common IO, try this:
public synchronized void log(String connID, String hotline, String callerType,
String cli, String lastMenu, String lastInput,
String status, String reason) {
String absoluteFP = LOG_LOC + ls + this.getFilename();
File file = new File(absoluteFP);
String message = this.getDateTime() + "," + connID + "," + hotline + "," + callerType + "," + cli + "," + lastMenu + "," + lastInput + "," + status + "," + reason;
try {
// note that you must explicitly add new line character if you want the line to end with newline
FileUtils.write(file, message + "\n", "UTF-8", true);
} catch (IOException ex) {
ex.printStackTrace ();
}
}
In Common IO 2.1, you can append a file that you are writting to. You can now get rid of the closePW and getPrintwriter and since the log method is synchronized, the file can be written one at a time from the same object. However, if you try to write the same file from different object at the same time, you will end up having overwritting problem.
Also, Common IO create the missing parent folder for you automatically. There is no need to explicitly check and create the folder.

Categories

Resources