I am trying to load image file from file directory. Then, I want to convert the file object to string object. Unfortunately, I keep receive this error messages. How can I resolve it?
java.io.FileNotFoundException: E:\workspace\sesaja\Images (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileInputStream.<init>(FileInputStream.java:79)
at test.Test1.main(Test1.java:29)
Thi is my overall code
public class Test1 {
public static void main(String args[]){
String s = System.getProperty("user.dir") + System.getProperty("file.separator")+ "Images";
File f = new File (s);
FileInputStream fis = null;
String str = "";
try {
fis = new FileInputStream(f);
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
str += (char) content;
}
System.out.println("After reading file");
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Concatenate desired file name at the end of this line:
String s = System.getProperty("user.dir") +
System.getProperty("file.separator")+ "Images" + fileName;
It seems you are trying to read data from a directory, which is not logically correct.
Also using FileInputStream in order to read characters (not data) is not recommended. You may use a BufferedReader instead.
Also for getting name of files inside a directory, you may read this: Read all files in a folder
Related
I wrote a code to read a files from a directory.
The directory contain many files. Firstly, I count the number of the files in the directory, then I would like to count number of lines in the files that have as extension: .info and .data
My code is the following:
public void checkEmptyEntryFileLoader(String directory) {
File name = new File(directory);
String filenames[]=name.list();
long countFile = 0;
long countLineData = 0;
long countLineInfo = 0;
for(String filename:filenames){
//System.out.println(filename);
countFile++;
}
System.out.println(countFile); // this bloc worked well
File files[]=name.listFiles();
for(File file:files){
String fileName = file.getName();
if(fileName.endsWith("data")) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.readLine() != null) {
countLineData++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fileName.endsWith("info")) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.readLine() != null) {
countLineInfo ++;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(countLineInfo );
}
}
I got as error:
java.io.FileNotFoundException: my_file_name.data (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
The error concerns the FileReader, it accept only the string, and the filename is a String
Do you have some idea please ?
Thank you
Instead of passing filename in FileReader(), try passing file.
BufferedReader reader = new BufferedReader(new FileReader(file));
My answer assumes that the error that you have given as output is stack trace printed in the try-catch block and not the error that you get when you try to compile/run the code.
The answer by #SARVESH TANDON looks like will fix your issue and note that you scan the filesystem twice.
Consider using NIO and streams to scan large file systems, as File.list / File.listFiles perform very badly when number of files get big, or you need to scan deeper as they need to be repeated.
Here is example of code using NIO. It uses a filter to restrict the search to only files of the right extension, and you can vary the find depth=1 parameter to Integer.MAX_VALUE for deep scans, and handles exceptions:
Path dir = Path.of(directory);
long[] counts = new long[3]; // FILES, MATCHFILES, LINECOUNT
try(Stream<Path> stream = Files.find(dir, 1, (p, a) -> ++counts[0] > 0 && a.isRegularFile())) {
stream.filter(p -> { String fn = p.getFileName().toString();
return (fn.endsWith("data") || fn.endsWith("info")) && ++counts[1] > 0; })
.forEach(p -> {
try(Stream<String> lines = Files.lines(p)) {
long count = lines.count();
counts[2]+=count;
System.out.println("path: "+p+" lines:"+count);
} catch (IOException io) {
throw new UncheckedIOException(io);
}
});
}
System.out.println("Total files: "+(counts[0]-1)); // dir is counted too
System.out.println("Match files: "+counts[1]);
System.out.println("Total lines: "+counts[2]);
I have been trying to duplicate a file but change the name of it in the same windows directory but I got not luck.
I cant just copy the file in the same directory because of the windows rule that two files cannot have the same name in the same directory.
I am not allowed to copy it to another directory then rename it, and then move it back in the same directory.
And I don't see any helpful implementation in the File.class.
Tried something like that but it didnt work:
File file = new File(filePath);
File copiedFile = new File(filePath);
//then rename the copiedFile and then try to copy it
Files.copy(file, copiedFile);
An initial attempt would be using Path as suitable:
Path file = Paths.get(filePath);
String name = file.getFileName().toString();
String copiedName = name.replaceFirst("(\\.[^\\.]*)?$", "-copy$0");
Path copiedFile = file.resolveSibling(copiedName);
try {
Files.copy(file, copiedFile);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
You could create a new file in the same directory and then just copy the contents of the original file to the duplicate
See: Java read from one file and write into another file using methods
For more info
you can also use this snippet from https://www.journaldev.com/861/java-copy-file
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
#Pierre his code is perfect, however this is what I use so I won't be able to change the extension:
public static void copyWithDifferentName(File sourceFile, String newFileName) {
if (sourceFile == null || newFileName == null || newFileName.isEmpty()) {
return;
}
String extension = "";
if (sourceFile.getName().split("\\.").length > 1) {
extension = sourceFile.getName().split("\\.")[sourceFile.getName().split("\\.").length - 1];
}
String path = sourceFile.getAbsolutePath();
String newPath = path.substring(0, path.length() - sourceFile.getName().length()) + newFileName;
if (!extension.isEmpty()) {
newPath += "." + extension;
}
try (OutputStream out = new FileOutputStream(newPath)) {
Files.copy(sourceFile.toPath(), out);
} catch (IOException e) {
e.printStackTrace();
}
}
I am testing something.
I created assets folder in packages/apps/Camera/ and added the test.txt file in the folder.
But when I accessed the file in the onCreate() method according the following code fragment, I found I can't get the file.
File file = new File("/assets/test.txt");
BufferedReader reader = null;
try {
Log.v("jerikc","read the file");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null) {
Log.v("jerikc","line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
Log.v("jerikc","exception");
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
The log were :
V/jerikc (3454): read the file
V/jerikc (3454): exception
I think I add the wrong path.("/assets/test.txt") .
So what's the right path?
Some other informations:
Where my real code is a Util Class, there isn't the context. If I add the context, the code structure will have a big change.
Thanks.
You have to read assets like below
AssetManager mAsset = context.getAssets();
InputStream is = mAsset.open("test.txt");
you can get the path from assest folder by this way...try this...
File file = new File("file:///assets/test.txt");
instead of this..
File file = new File("/assets/test.txt");
I am trying to create a block that writes a file when the file doesn't exsist, but it has turned into a Catch-22. The file doesn't exist, so it can't write the file so it can exsist. Here is my attempt:
if(!FileReadWrite.file2.exists())
FileReadWrite.fileWrite();
public static File file2 = new File("./settings.txt");
public static void fileWrite()
{
try
{
FileWriter fstream = new FileWriter(file2);
BufferedWriter out = new BufferedWriter(fstream);
String c = Byte.toString(Textures.a);
out.write(c);
out.close();
}catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
int ch;
StringBuffer strContent = new StringBuffer("");
InputStream fin = null;
try
{
fin = new FileInputStream(file2);
while ((ch = fin.read()) != -1)
{
strContent.append((char) ch);
}
fin.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
I am using Eclipse. The file is in the bin folder, but when I export it to a jar it is outside the jar folder.
Exception in thread "main" java.lang.ExceptionInInitializerError
at srcD.Main.<init>(Main.java:19) //(FileReadWrite.fileWrite())
at srcD.Main.main(Main.java:129) //(Make JFrame)
Caused by: java.lang.NullPointerException
at srcD.FileReadWrite.<clinit>(FileReadWrite.java:7) //(public file...)
... 2 more
I think this ClassLoader.getSystemResource("settings.txt") code returns null and .getFile() gets an NPE
Answer to comment
Firstly you should understand that method getSystemResource NOT for outside resources read this
For load outside resources from jar you have to use full path to resource, full != absolute,
how to find full path
start point + path to resource
For example we have next files structure /Users/fakeuser/tetsproject/ - this folder contains your jar and conf folder contains or should contain settings.txt, if you have delivery structure like this your code will be
public static File file2 = new File("./conf/settings.txt");
And that is all.
I'm trying to open a file in android like this :
try
{
FileInputStream fIn = context.openFileInput(FILE);
DataInputStream in = new DataInputStream(fIn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
if(in!=null)
in.close();
}
catch(Exception e)
{ }
, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.
I think the best way to know if a file exists, without actually trying to open it, is as follows:
File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...
The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
So it looks like the exception is your "test".
You could also try using standard
java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
FileInputStream fIn = new FileInputStream(file);
}
But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get
deleted when your app gets uninstalled.
With the standard java.io.File this is the function I have created, and works correctly:
private static final String APP_SD_PATH = "/Android/data/com.pkg.myPackage";
...
public boolean fileExistsInSD(String sFileName){
String sFolder = Environment.getExternalStorageDirectory().toString() +
APP_SD_PATH + "/Myfolder";
String sFile=sFolder+"/"+sFileName;
java.io.File file = new java.io.File(sFile);
return file.exists();
}
why dont you just catch the FileNotFound exception and take that as the file not being present.
If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
e.g.
{
String pathName = <file path name>
File file = new File (pathName);
Uri pathURI = Uri.fromFile (file);
boolean created;
String mIOException = "";
String mSecException = "";
try
{
created = file.createNewFile();
if (created)
{
ctxt.sendBroadcast (new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pathURI));
}
}
catch (IOException ioex)
{
mIOException = ioex.getMessage();
}
catch (SecurityException sex)
{
mSecException = sex.getMessage();
}
}
If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:
public static void write_custom_log(String message){
File root = Environment.getExternalStorageDirectory();
try{
BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/mnt/sdcard/tjb_tests/tjb_log_file.txt"),true));
if (root.canWrite()){
fw.write(message);
fw.close();
}
} catch (IOException e) {
Log.e("One", "Could not write file " + e.getMessage());
}
}
My suggestion is to check length of the file. if file.length() returns 0 that means file doesn't exist.