I try a lot of thinks to find the fail but i don't know how I can do it. my code is:
//DominioLlamadaRedSys.java
Properties d = new Properties();
InputStream entrada = null;
try {
entrada = new FileInputStream("prop/datosApp.properties");
d.load(entrada);
System.out.println(d.getProperty("TXD.endPointUrl"));
} catch (IOException ex) {
System.out.println("ERROR: "+ ex.getMessage());
} finally {
if (entrada != null) {
try {
entrada.close();
} catch (IOException e) {
}
}
}
I call the file inside a class in "com.rsi.secpay.dominio" and this always catch the same exception (don't find the file), I had try to quit "prop/" (just "datosApp.properties" ) with properties files like this:
If your prop package is in your classpath, you can get the stream using the classloader:
InputStream is = DominioLlamadaRedSys.class.getResourceAsStream("/prop/datosApp.properties");
Related
This properties file in PROJECT/resources/properties.properties can be read and show its content with:
public void showFileContent(String fileName){
File file = new File (fileName);
FileInputStream input = null;
if(file.exists()){
int content;
try {
input = new FileInputStream(fileName);
while ((content = input.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("Error : properties File " + fileName + " not found");
}
}
But it fails with a null pointer exception at properties.load with that code
public Properties getProperties(String fileName, Properties properties){
File file = new File (fileName);
InputStream input = null;
if(file.exists()){
try {
input = new FileInputStream(fileName);
properties.load(input);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("Error : properties File " + fileName + " not found");
}
return properties;
}
even when input is set to
input = this.getClass().getClassLoader().getResourceAsStream(fileName)
anyone knows why that can be for a properties text file at the same path for both methods ?
Since the first code snippet works, it seems properties is passed as null to the getProperties() method, resulting in NullPointerException.
Ideally, we shouldn't be passing the properties at all. We just need to create a new object and return it.
using IOUtils.write to write a string to a file
try {
IOUtils.write("test", new FileWriter(configFile));
} catch (Exception e) {
e.printStackTrace();
}
where configfile is the location of the configuration file ("./resources/config.json")
This seems to delete the file and replace it with a file that has no contents.
no exceptions are thrown either.
Make sure to close the stream after use, else the data might not be written to the file.
FileWriter fw=null;
try {
fw= new FileWriter(configFile);
IOUtils.write("test",fw);
}catch (Exception e) {
e.printStackTrace();
}finally
{
IOUtils.closeQuietly(fw);
}
You need to close the writer, or use try with resources. Otherwise everything might not be flushed to disk:
try (FileWriter fw = new FileWriter(configFile)) {
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
}
Try this code:
FileWriter fw = null;
try {
fw = new FileWriter(configFile);
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fw != null)
fw.close();
}
I am using NIO File Channel to manage files, and locking them. So far it works, however when I lock a File using NIO File Lock it locks the file so the file Content cannot be changed. As for example if I try to edit a text file on notepad it will show me the following error message:
And that is the expected result, however if I try to delete the file from windows explorer(I haven't tested on other OS likely will be possible as well) it will allow me, and this is undesired, I would like to know if it is possible to Open a File Handle
Code Used:
private static final byte[] MessageBytes;
static {
byte tmp[];
try {
tmp = "Hello World".getBytes("UTF-8");
} catch (UnsupportedEncodingException ex) {
//if fail get the bytes in whatever the java VM charset sets as default
tmp = "Hello World".getBytes();
}
MessageBytes = tmp;
}
private static final String Filename = "Lock_test.txt";
private static void createFileandLock() {
Path FilePath = Paths.get(Filename);
FileChannel OpenFCh;
try {
OpenFCh = FileChannel.open(FilePath, StandardOpenOption.CREATE,
StandardOpenOption.READ, StandardOpenOption.WRITE
// ,StandardOpenOption.APPEND
);
System.out.println("File Channel is Open.");
} catch (IOException err) {
OpenFCh = null;
}
if (OpenFCh != null) {
FileLock Lock = null;
try {
Lock = OpenFCh.lock();
} catch (IOException err) {
System.out.println("Unable To Lock the File.");
}
try {
OpenFCh.write(ByteBuffer.wrap(MessageBytes));
OpenFCh.force(false);
System.out.println("Message Recorded");
} catch (IOException ex) {
System.out.println("Unable To write data into file");
}
try {
// at this point file still locked and open.
//lets wait for input and meanwhile ask to delete the file.
System.out.print("Please Try to delete file at: ");
System.out.println(FilePath.toString());
System.out.println("Press Enter to Continue");
System.in.read();
} catch (IOException ex) {
}
if (Lock != null) {
try {
Lock.close();
} catch (IOException ex) {
}
}
try {
OpenFCh.close();
} catch (IOException ex) {
}
}
}
After further research I notice that using RandomAccessFile Will lock the file avoiding deletion as it creates a File Descriptor that basically open a Handle on the underline Operative system.
So using the RAF does provide the desired result:
Code Used:
private static void createRAFileandLock() {
RandomAccessFile RAf;
try {
RAf = new RandomAccessFile(Filename, "rw");
} catch (FileNotFoundException ex) {
//since is open as RW shold not trigger.
RAf = null;
}
if (RAf != null) {
FileChannel OpenFCh = RAf.getChannel();
FileLock Lock = null;
try {
Lock = OpenFCh.lock();
} catch (IOException err) {
System.out.println("Unable To Lock the File.");
}
try {
OpenFCh.write(ByteBuffer.wrap(MessageBytes));
OpenFCh.force(false);
System.out.println("Message Recorded");
} catch (IOException ex) {
System.out.println("Unable To write data into file");
}
// at this point file still locked and open.
//lets wait for input and meanwhile ask to delete the file.
try {
System.out.print("Please Try to delete file at: ");
System.out.println(Filename);
System.out.println("Press Enter to Continue");
System.in.read();
} catch (IOException ex) {
}
if (Lock != null) {
try {
Lock.close();
} catch (IOException ex) {
}
}
try {
OpenFCh.close();
RAf.close();
} catch (IOException ex) {
}
}
}
However I would like to know if it is possible to archive this using only NIO. As Random Access File is on IO package.
FileLock isn't specified to prevent deletion. It's only specified to interact with other file locks, so you're already deep into platform-dependent behaviour. If RandomAccessFile somehow does what you want you may be stuck with it, but you can't rely on it.
NB of course FileChannel.open() uses a FileDescriptor, handle, etc.
I'm trying to detect a file content type passed to a web service into the SOAP envelop.
This file can be indicated in two ways :
from its url,
from its contain (base64 compressed data).
At this point, I'm able to translate this file into a stream buffer.
But, all my tries to get its content type failed.
The content type is detected if the file extension is indicated otherwise the content is always detected as "plain/text".
Bellow is my class code :
class MetadataAnalyser {
private InputStream _is;
private File _file;
private void initializeAttributes() {
_is = null;
_file= null;
}
private void createTemporaryFile(byte[] pData) {
FileOutputStream fos = null;
try {
_file = File.createTempFile(
UUID.randomUUID().toString().replace("-", ""),
null,
new File("C:\\Users\\Florent\\Documents\\NetBeansProjects\\ServiceEdition\\tmp"));
} catch (IOException e) {
e.printStackTrace();
}
try {
fos = new FileOutputStream(_file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(pData);
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
_file.deleteOnExit();
}
public MetadataAnalyser(byte[] pData) {
initializeAttributes();
_is = new ByteArrayInputStream(pData);
createTemporaryFile(pData);
}
public MetadataAnalyser(InputStream pIs) {
initializeAttributes();
_is = pIs;
_file = null;
}
public MetadataAnalyser(File pFile) {
initializeAttributes();
try {
_file = pFile;
_is = new FileInputStream(_file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public MetadataAnalyser(String pFile) {
initializeAttributes();
try {
_file = new File(pFile);
if (_file.exists()) {
_is = new FileInputStream(_file);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getContentType() {
AutoDetectParser parser = null;
Metadata metadata = null;
InputStream is = null;
String mimeType = null;
parser = new AutoDetectParser();
parser.setParsers(new HashMap<MediaType, Parser>());
metadata = new Metadata();
if(_file != null) {
metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, _file.getName());
}
try {
is = new FileInputStream(_file);
parser.parse(is, new DefaultHandler(), metadata, new ParseContext());
mimeType = metadata.get(HttpHeaders.CONTENT_TYPE);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
} finally {
return mimeType;
}
}
}
So, how to detect the MIME type even if the file extension is unknown ?
I don't think you can detect the mime type without extension , you would need to know which system is writing the file and what kind of file is expected to be there and based on that you need to set the MIME type(I guess you are using it in your response).
You need to make sure the content is decoded before being sent to Tika and no, the extension is absolutely not needed, the detection happens via a well understood mime magic process described here: https://tika.apache.org/1.1/detection.html
I need to save an arraylist of hashmaps to an external file. I can use any format expect for a text file, because the program is set to ignore text files (specially, anything with a .txt extension). The hashmaps are pretty straightforward, just words with counts of those words. What is the ideal file format to store this in?
You could use java.util.Properties.
Properties properties = new Properties();
properties.putAll(yourMap); // You could also just use Properties in first place.
try (OutputStream output = new FileOutputStream("/foo.properties")) {
properties.store(output, null);
}
You can read it later by
Properties properties = new Properties();
try (InputStream input = new FileInputStream("/foo.properties")) {
properties.load(input);
}
// ... (Properties implements Map, you could just treat it like a Map)
See also:
Java Tutorials - Essential Classes - Properties
You could use serialization:
ObjectOutputStream stream = null;
try
{
File f = new File(filename);
stream = new ObjectOutputStream(new FileOutputStream(f));
stream.writeObject(your_arraylist);
}
catch (IOException e)
{
// Handle error
}
finally
{
if (stream != null)
{
try
{
stream.close();
}
catch (Exception e) {}
}
}
And read it in using:
ObjectInputStream stream = null;
try
{
stream = new ObjectInputStream(new FileInputStream(f));
your_arrayList = (your_arrayList type here)stream.readObject();
}
catch (Throwable t)
{
// Handle error
}
finally
{
if (stream != null)
{
try
{
stream.close();
}
catch (Exception e) {}
}
}