Can't find file Resource when filename contain with "#" using Spring - java

I found error when filename contain with "#".
Error: java.lang.IllegalStateException: File does not exist.
But when filename without "#" still working.
String resource = "file:c:/Test#.txt";
PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
Resource[] resolveResources;
try {
resolveResources = pathResolver.getResources(resources);
if(resolveResources.length == 0) {
throw new IllegalStateException("File does not exist: " + resources);
}else{
for (Resource resource : resolveResources) {
if(!resource.exists()){ //true
throw new IllegalStateException("File does not exist: " + resource);
}
}
}
} catch (IOException e) {
throw new IllegalStateException("File does not exist: " + resources);
}

file names validity depends on operating system (the file system to be more accurate), so to make sure that the file can be read on any Operating system; use alphanumeric and the underscoreCharacters to avoid
in your program the problem is in the URI making function
public static void main(String[] args ){
File f = new File("ahh#.txt");
try {
if(f.createNewFile()){
System.out.println("ok"+ f.getAbsolutePath());
}
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
// file with string path
FileInputStream fis0;
try {
fis0 = new FileInputStream(
new File(f.getAbsolutePath()));
} catch (FileNotFoundException ex) {
System.out.println("file not found with string");
}
try {
try {
// file with URI
FileInputStream fis1 =
new FileInputStream(
new File(
new URI(f.getAbsolutePath())));
} catch (URISyntaxException ex) {
System.out.println("URI???");
}
} catch (FileNotFoundException ex) {
System.out.println("file not found with URI");
}
}

It's a bit of a hack but I think you need something like this :
#Test
public void test1() {
try {
String resource = "file:c:\\tmp\\Test\u0023.txt";
PathMatchingResourcePatternResolver pathResolver = new TestPathMatchingResourcePatternResolver();
Resource[] resolveResources;
resolveResources = pathResolver.getResources(resource);
if (resolveResources.length == 0) {
throw new IllegalStateException("File does not exist: " + resource);
} else {
for (Resource resource2 : resolveResources) {
if (!resource2.exists()) { // true
throw new IllegalStateException("File does not exist: " + resource2);
}
}
}
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
Then you need to add modify the PathMatchingResourcePatternResolver
public class TestPathMatchingResourcePatternResolver extends PathMatchingResourcePatternResolver {
public TestPathMatchingResourcePatternResolver() {
super(new TestDefaultResourceLoader());
}
}
Then you need to modify the DefaultResourceLoader
public class TestDefaultResourceLoader extends DefaultResourceLoader {
#Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
if (location.startsWith("/")) {
return getResourceByPath(location);
} else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
} else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return new TestUrlResource(url);
} catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}
}
Then you need to modify the UrlResource
public class TestUrlResource extends UrlResource {
public TestUrlResource(URL url) {
super(url);
}
#Override
public boolean exists() {
return true;
}
#Override
public File getFile() throws IOException {
return new File(getURL().toString().replace("file:", ""));
}
}

Related

How to Adding Restore setting feature by FileinputStream

So I am new in programing and i adding a feature in my app which save all sharedpreference key in value in Device internal data folder by using fileoutputStream like this add all data in map and store in jsonobject
private String maptojson(){
Map<String, ?> map = prf.getAll();
JSONObject object = new JSONObject();
for (Map.Entry<String,?> entry : map.entrySet()){
try {
object.put( entry.getKey(), entry.getValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
return object.toString();
}
Now Use FileOutputStream for write file in internal Storage "data'
public void backupSetting() {
Throwable th;
FileOutputStream fileOutputStream;
IOException e;
FileOutputStream fileOutputStream2 = null;
File externalStorageDirectory = Environment.getExternalStorageDirectory();
if (externalStorageDirectory.exists() && externalStorageDirectory.canWrite()) {
if (externalStorageDirectory.getUsableSpace() >= 1048576) {
File file = new File(externalStorageDirectory.toString() + "/data/MyApp/" + "MyAppSetting.ma");
try {
new File(file.getParent()).mkdirs();
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
try {
fileOutputStream.write(maptojson().getBytes());
fileOutputStream.flush();
fileOutputStream.close();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
} catch (IOException e3) {
e = e3;
try {
e.printStackTrace();
if (fileOutputStream != null) {
}
} catch (Throwable th2) {
th = th2;
fileOutputStream2 = fileOutputStream;
if (fileOutputStream2 != null) {
try {
fileOutputStream2.close();
} catch (IOException e4) {
e4.printStackTrace();
throw th;
}
}
throw th;
}
}
} catch (IOException e5) {
e = e5;
fileOutputStream = null;
e.printStackTrace();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e6) {
e6.printStackTrace();
}
}
} catch (Throwable th3) {
th = th3;
if (fileOutputStream2 != null) {
}
try {
throw th;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
}
Now i want to add restore setting means restore setting by using that file "MyAppSetting.ma". I know i can do it by using FileInputStream but I don't understand how to do? please help if you could

Property file is returning as null in Java

I am trying to read some property from the properties file, but my code is not reading the property file. The properties file is in some folder in my machine.
Here is my code:
public String getproperty(){
String extension="";
Properties prop = new Properties ();
String propname = "\\"+Any location in your machine+"\\fileExtension.properties";
Logger.debug("ReadFiles", " ----Property file path---- "+ propname, null);
ip = getClass().getClassLoader().getResourceAsStream(propname);
Logger.debug("ReadFiles", " ----ip value ---- "+ip, null);
try {
if(ip != null){
prop.load(ip);
Logger.debug("ReadFiles", " ----Property file loaded---- ", null);
}
extension = prop.getProperty("fileExt");
Logger.debug("ReadFiles", " ----Property = " + extension, null);
} catch (IOException e) {
Logger.error("ReadFiles", " ----Error while loading property file---- ", null);
e.printStackTrace();
}
finally{
try {
ip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return extension;
}
I am creating a jar placing it in lib folder of server (installed in my machine) and placing the properties file in my machine and given the same path in code. I have tried with absolute path and without absolute path.
Please try this example that uses an absolute path to the properties file.
package com.company;
import java.io.*;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("/home/dac/gs-rest-service/javacode/src/main/java/com/company/config.properties");
prop.load(input);
String extension = prop.getProperty("fileExt");
System.out.println("ReadFiles ----Property = " + extension);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Test
cat /home/dac/gs-rest-service/javacode/src/main/java/com/company/config.properties
#Mon Dec 26 17:31:30 CET 2016
dbpassword=password
database=localhost
dbuser=foobar
fileExt=.xml⏎
Run the program
ReadFiles ----Property = .xml

save a created propertyfile in specific folder

How can I save a prop file in a specific folder for example,
now it is saved in the root I guess, but it needs to be in the same folder as the class where it is created.
I also want to know how to load it. If it possible to load a properties file easily from the root then it is okay as well to save it in the root.
code creating the file, first 2 lines with // ( = make code work now without using prop file), class name = Providers
public static DataAccessProvider createProvider (URL url) {
//MovieDAOOnline mdaoOn = new MovieDAOOnline();
//mdaoOn.setUrl(url);
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("uri", url.toString());
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new OnlineProvider();
}
code for getting the file, first line in comment needs to be changed to get uri from propertie:
public Movie getMovie(int id) throws DataAccessException{
//StringBuilder builder = new StringBuilder(url.toString());
builder.append("movies.xml");
MovieConfigRead mcr = new MovieConfigRead();
List<Movie> film = null;
try {
film = mcr.geefMovies(builder.toString());
} catch (JAXBException e) {
throw new DataAccessException();
} catch (MalformedURLException e) {
throw new DataAccessException();
}
for (Movie movie : film) {
if (movie.getId() == id) {
return movie;
}
}
return null;
}

Create file inside folder "resources" of spring project

In my current spring, some forms have a field where the user can upload a file, which should be saves inside the folder resources from project (src/main/resources, following the structure created by maven).
the method responsible for save the file in this folder is working ok until this line:
URL path = this.getClass().getClassLoader().getResource(file);
the variable path is staying with the value null. the variable file is defined with this value:
String file = "/"+this.getName()+"/"+String.valueOf(id)+"/picture.jpg";
Anyone can tell me the right way to do this?
PS.: the complete code for this method is:
public boolean upload_picture(E e, MultipartFile f) {
Integer id = null;
if(f == null) {
return false;
}
Class<?> clazz = e.getClass();
Method methods[] = clazz.getDeclaredMethods();
for(int i=0; i<methods.length; i++) {
if(methods[i].getName().equals("getId")) {
try {
id = (Integer) methods[i].invoke(e);
} catch (IllegalAccessException e1) {
e1.printStackTrace();
return false;
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
return false;
} catch (InvocationTargetException e1) {
e1.printStackTrace();
return false;
}
}
}
BufferedImage src;
try {
src = ImageIO.read(new ByteArrayInputStream(f.getBytes()));
} catch (IOException e3) {
e3.printStackTrace();
return false;
}
String file = "/"+this.getName()+"/"+String.valueOf(id)+"/picture.jpg";
URL path = this.getClass().getClassLoader().getResource(file);
File destination;
try {
destination = new File(path.toURI());
} catch (URISyntaxException e2) {
destination = new File(path.getPath());
e2.printStackTrace();
}
try {
ImageIO.write(src, "jpeg", destination);
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}

From clipboard to file

I want to get data from the clipboard and store it in a .txt file.
How do I create the .txt file? I have read a lot about getting data from a file but not the other way around.
Here is my code:
public void CallClipboard (){
System.out.println("Copying text from system clipboard.");
String grabbed = ReadClipboard();
System.out.println(grabbed);
}
public String ReadClipboard () {
// get the system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// get the contents on the clipboard in a
// transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if clipboard is empty
if (clipboardContents.equals(null)) {
return ("Clipboard is empty!!!");
}
else
try {
// see if DataFlavor of
// DataFlavor.stringFlavor is supported
if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// return text content
String returnText = (String) clipboardContents.getTransferData(DataFlavor.stringFlavor);
return returnText;
}
}
catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
I have solved it with the current code thanx for the tips
public static void CallClipboard (String file){
System.out.println("Copying text from system clipboard.");
String grabbed = ReadClipboard(file);
System.out.println(grabbed);
}
public static String ReadClipboard (String file) {
File testFile = new File(file);
// get the system clipboard
Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// get the contents on the clipboard in a
// transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if clipboard is empty
if (clipboardContents.equals(null)) {
return ("Clipboard is empty!!!");
}
else
try {
// see if DataFlavor of
// DataFlavor.stringFlavor is supported
if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// return text content
String returnText = (String) clipboardContents.getTransferData(DataFlavor.stringFlavor);
try {
setContents(testFile, returnText);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return returnText;
}
}
catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
static public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
//use buffering
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
//FileWriter always assumes default encoding is OK!
output.write( aContents );
}
finally {
output.close();
}
}
Take a look at FileWriter and BufferedWriter for writing Strings to files.

Categories