I have to read a file which can be local or in remote.
The file path or URI will come form user input.
Currently I am reading only local file,this way
public String readFile(String fileName)
{
File file=new File(fileName);
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(file));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ( (line=bufferedReader.readLine())!=null ) {
stringBuilder.append(line);
stringBuilder.append(System.lineSeparator());
}
return stringBuilder.toString();
} catch (FileNotFoundException e) {
System.err.println("File : \""+file.getAbsolutePath()+"\" Not found");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
The parameter String fileName is the user input which can be a path to local file or a URI
How can i modify this method to work with both Local path and URI ?
Suposing you have the URI in String fileName you can read url easily with:
URI uri = new URI(filename);
File f = new File(uri);
Check this link for further info
File class has also a constructor based on the URI so it easy to say new File(uri).. and everything stays the same.
However, the URI is system-dependent, as specification says "An absolute, hierarchical URI with a scheme equal to "file", a non-empty path component, and undefined authority, query, and fragment components".
I think that if you need to read something remote, the best way to do it is by using Sockets.
Related
After reading a file, I'm trying to delete it, but the following error appears:
java.io.IOException: Unable to delete file test.zip at
org.apache.commons.io.FileUtils.forceDelete (FileUtils.java:1390) at
org.apache.commons.io.FileUtils.cleanDirectory (FileUtils.java:1044)
at org.apache.commons.io.FileUtils.deleteDirectory
(FileUtils.java:977)
Here is my code. I've been careful to close the InputStream in the finally clause and only then call the method that deletes the file, but even then I can only delete it when I stop the program.
InputStream is = null;
try {
is = new URL(filePath).openStream(); // filePath is a string containing the path to the file like http://test.com/file.zip
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
String xml = sb.toString(); // this code is working, the result of the "xml" variable is as expected
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
removeFileAndFolder(absolutePath);
}
private void removeFileAndFolder(String absolutePath) {
new Thread(new Runnable() {
#Override
public void run() {
try {
String folder = getFolder(absolutePath); // this method just get the path to the folder, because I want to delete the entire folder, but the error occurs when deleting the file
FileUtils.deleteDirectory(new File(folder));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
After some tests I discovered that I can manually delete the file just before the line "is = new URL (filePath) .openStream ();". After it, and even after the line "is.close ();" I can not delete the file manually unless I stop the program.
I got it. I was opening the file by the url (is = new URL(filePath).openStream();), and trying to delete it by absolute path. I changed it to "is = new FileInputStream(absoluteFilePath);" and it works!
I am trying to read values from CSV file which is present in package com.example.
But when i run code with the following syntax:
DataModel model = new FileDataModel(new File("Dataset.csv"));
It says:
java.io.FileNotFoundException:Dataset.csv
I have also tried using:
DataModel model = new FileDataModel(new File("/com/example/Dataset.csv"));
Still not working.
Any help would be helpful.
Thanks.
If this is the FileDataModel from org.apache.mahout.cf.taste.impl.model.file then it can't take an input stream and needs just a file. The problem is you can't assume the file is available to you that easily (see answer to this question).
It might be better to read the contents of the file and save it to a temp file, then pass that temp file to FileDataModel.
InputStream initStream = getClass().getClasLoader().getResourceAsStream("Dataset.csv");
//simplistic approach is to put all the contents of the file stream into memory at once
// but it would be smarter to buffer and do it in chunks
byte[] buffer = new byte[initStream.available()];
initStream.read(buffer);
//now save the file contents in memory to a temporary file on the disk
//choose your own temporary location - this one is typical for linux
String tempFilePath = "/tmp/Dataset.csv";
File tempFile = new File(tempFilePath);
OutputStream outStream = new FileOutputStream(tempFile);
outStream.write(buffer);
DataModel model = new FileDataModel(new File(tempFilePath));
...
public class ReadCVS {
public static void main(String[] args) {
ReadCVS obj = new ReadCVS();
obj.run();
}
public void run() {
String csvFile = "file path of csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// Do stuff here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
CSV file which is present in package com.example
You can use getResource() or getResourceAsStream() to access the resource from within the package. For example
InputStream is = getClass().getResourceAsStream("/com/example/Dataset.csv");//uses absolute (package root) path
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//read from BufferedReader
(note exception handling and file closing are omitted above for brevity)
How to call application servlet from java class with relative path.
I want to call with GET method
/myServlet
from
myClass.
EDIT
So far i find:
BufferedReader in = null;
URL url = null;
try {
url = new URL("http://localhost:8080/myApp/myServlet");
in = new BufferedReader(new InputStreamReader(url.openStream()));
result = in.readLine();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) in.close();
} catch (IOException e) { }
}
but as i said i want to call a servlet with relative path. Not to decler hostname and appName.
I want to write data to an output file and save it on a mobile device or on a computer harddrive. I am able to get my code below to work, but have to create the directory in one step and then create the file in another. Is there a more effective way to code having to create an non-existing directory before writing a file there?
Thanks
StringBuilder Path = new StringBuilder();
Path.append(Environment.getExternalStorageDirectory().toString());
String filename = "test.txt";
String test_text = "Date, Item, Quantity, Description,";
File file = new File(Path.toString()+"/" +"Test Folder2/");
file.mkdirs();
FileOutputStream file_os = null;
try {
File file2 = new File(Path.toString()+"/" +"Test Folder2", filename);
file_os = new FileOutputStream(file2);
OutputStreamWriter osw = new OutputStreamWriter(file_os);
try {
osw.write(test_text);
} catch (IOException e) {
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
Toast.makeText(QuizSettingsActivity.this, Path.toString(),
Toast.LENGTH_LONG).show();
};
String FILENAME = "test";
String string = "Date, Item, Quantity, Description,";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
For more detail on saving file on external storage follow the link mentioned below:.http://developer.android.com/guide/topics/data/data-storage.html
How do I get the path of a an executed .jar file, in Java?
I tried using System.getProperty("user.dir"); but this only gave me the current working directory which is wrong, I need the path to the directory, that the .jar file is located in, directly, not the "pwd".
Could you specify why you need the path?If you need to access some property from the jar file you should have a look at ClassLoader.getSystemClassLoader();
don't forget that your classes are not necessary store in a jar file.
// if your config.ini file is in the com package.
URL url = getClass().getClassLoader().getResource("com/config.ini");
System.out.println("URL=" + url);
InputStream is = getClass().getClassLoader().getResourceAsStream("com/config.ini");
try {
if (is != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
else {
System.out.println("resource not found.");
}
}
catch (IOException e) {
e.printStackTrace();
}
regards.
Taken From Java-Forumns:
public static String getPathToJarfileDir(Object classToUse) {
String url = classToUse.getClass().getResource("/" + classToUse.getClass().getName().replaceAll("\\.", "/") + ".class").toString();
url = url.substring(4).replaceFirst("/[^/]+\\.jar!.*$", "/");
try {
File dir = new File(new URL(url).toURI());
url = dir.getAbsolutePath();
} catch (MalformedURLException mue) {
url = null;
} catch (URISyntaxException ue) {
url = null;
}
return url;
}
Perhaps java.class.path property?
If you know the name of your jar file, and if it is in the class path, you can find its path there, eg. with a little regex.