Iam trying to add a path (string) over an editfield in class main, the path will be taken to another class extract. After this I want to read the file with FileReader, but I got some error: file not found.
So I does some test:
I wrote the path directly in the FileReader -> everything Okay
I wrote a function File named sFile to get the path from class main and try to find the file behinde the path (exists). The file could be found but if FileReader trying to load the file got the same error
Code:
File sFile = new File(path);
if (sFile.exists()){
System.out.println("Found.");
System.out.println(sFile.getAbsolutePath());
try{
FileReader file = new FileReader(sFile); //db10916358-hp.sql (test file)
String[] fReadTmp = new String[10240000];//Just for testing
BufferedReader br = new BufferedReader(file);
String read = br.readLine();//Read a line
I found the error, it was an other File function which creates some files from the extract.
It was so simple, sorry for that.
Thanks for your time!
Try this snippet of code its work correctly
public static void readFile(String path) throws FileNotFoundException, IOException{
File file = new File(path);
if(file.exists())
{
FileReader fileReader = new FileReader(file); //db10916358-hp.sql (test file)
BufferedReader br = new BufferedReader(fileReader);
String read = br.readLine();//Read a line
}
else
{
System.out.print("Not Found");
}
}
Related
I added a text file to my project as in this path:
Myproject/WebPages/stopwords.txt
Image:
http://s7.postimg.org/w65vc3lx7/Untitled.png
I tried to open the file, but i can't !
My code:
BufferedReader br = new BufferedReader(new FileReader("stopwords.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
Error:
stopwords.txt (The system cannot find the path specified)
You can try something like,
I guess that you are in .jsp file.
<%
String path = request.getServletContext().getRealPath("/WebContent/stopwords.txt") ;
BufferedReader br = new BufferedReader(new FileReader(path));
// other codes...
%>
EDITED :
<%
String path = request.getServletContext().getRealPath("/stopwords.txt") ;
//check here with print path variable...
// you can pass this path variable to invoke method which is reside into //your java class...
BufferedReader br = new BufferedReader(new FileReader(path));
%>
The FileReader will be opening the file relative to the path this is executed from. If this is being executed from the "MyProject" folder, you will need to specify the folder in the FileReader constructor as in FileReader("WebPages/stopWords.txt")
If your projectpath is the root folder. Where the class is isn't where the root folder is. Changing it to this should work. You also need to add a space to your filename.
BufferedReader br = new BufferedReader(new FileReader("/Web Pages/stopwords.txt"));
empirical method:
begin to create and write some file => then you will see where it is on the filesystem
then place you file in the same directory, and retry others methods to read it
warning: sometimes, you cant read or write in some directories.
I have the below java code in which i am passing a file name to the the calling method lets say below code is initially the code is
File file = new File("C:\\oabc.csv");
String filename = file.getName();
s = getFileExtension(file) ;
if (s.equalsIgnoreCase(".csv"))
{
convertcsvtoexcel(filename);
}
now since there is an csv file that is being passed so it will call the method to convert the csv to excel till that stage i have tried to debug i am getting the filename but below is the convert code that is called in which it not find the filename throwing an exception that file not found exception
public static void convertcsvtoexcel(String filename) throws Exception {
ArrayList arList=null;
ArrayList al=null;
String thisLine;
int count=0;
FileInputStream file1 = null ;
file1 = new FileInputStream(new File(filename));
DataInputStream myInput = new DataInputStream(file1);
int i=0;
But it in the above code it throws the error at line file1 = new FileInputStream(new File(filename)); saying that it does not found file abc.csv at the specified location
getName() returns the file name without any directory information, so in
String name=file.getName();
File file2=new File(name);
file2 and file are not pointing to the same file, unless file is in the current directory.
In your code, pass a File object to your method to avoid path conversion issues.
You should use convertcsvtoexcel(getPath()).
in the following line of code you are just passing the file name.To make it work pass the entire file path + file name.
file1 = new FileInputStream(new File(filename));
file1 = new FileInputStream(new File("C:\\oabc.csv")); this should work.
This one's a fun one. I'd appreciate any bit of help, and no previous stackoverflow questions are pointing me in the right location. Docs also weren't very helpful to me.
I'm being thrown a FileNotFoundException with this block of code:
public static int wordOccurance(Word t, File D) throws FileNotFoundException
{
int occurance = 0;
BufferedReader mainReader = new BufferedReader(new FileReader(D));
Scanner kb = new Scanner(mainReader);
My tester file does not cause this to occur: ie. "File tester = new File("C:\read.txt");"
But the problem occurs solely when I pass a File constructed by this method:
public static File makeAndCombineFile(String FileOne, String FileTwo) throws IOException
{
BufferedReader mainReader = null;// null holder value for the later useful bufferedReader
Scanner kb = null;// null holder for later useful Scanner
StringBuilder sb = new StringBuilder();
OTHER CONDITIONS BETWEEN THESE TWO CHUNKS. MOST LIKELY NOT PERTINENT. ALSO RETURN FILE, JUST IF ONE INPUT IS NULL.
else //in case both are good to go and obviously not null
{
mainReader = new BufferedReader(new FileReader(FileOne));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine() + "\n");
mainReader = new BufferedReader(new FileReader(FileTwo));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine()+ "\n");
kb.close();
return new File(sb.toString());
}
}
It took me a while to figure out what was going on here, but it looks to me like you think that this line:
return new File(sb.toString());
creates a file on disk containing the text read from the two scanners. It does not. It creates a java.io.File, which is basically a representation of a file path; the path represented by this File is the data read from the scanners. In other words, if FileOne and FileTwo contained the text to War and Peace, then the path represented by that file would be the the text of War and Peace. The file will not have been created on disk; no data will have been written to it. You've just created an object that refers to a file that does not exist.
Use a FileWriter, perhaps in conjunction with a PrintWriter, to save the lines of text into a file; then you can create a File object containing the name of that file and pass it to your other routine:
PrintWriter pw = new PrintWriter(new FileWriter("somename.txt"));
while(kb.hasNext())
pw.println(kb.nextLine());
pw.close();
return new File("somename.txt");
I have a directory in my jar called "lessons". Inside this directory there are x number of lesson text files. I want to loop through all these lessons read their data.
I of course know how to read a file with an exact path:
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/lesson1.lsn")));
try{
in.readLine();
}catch(IOException e){
e.printStackTrace();
}
But what I want is something more like this:
File f = new File(Main.class.getResource("lessons"));
String fnames[] = f.list();
for(String fname : fnames){
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/" + fname)));
in.readLine();
}
File however doesn't take a URL in it's constructor, so that code doesn't work.
I will use junit.jar in my test as an example
String url = Test1.class.getResource("/org/junit").toString();
produces
jar:file:/D:/repository/junit/junit/4.11/junit-4.11.jar!/org/junit
lets extract jar path
String path = url.replaceAll("jar:file:/(.*)!.*", "$1");
it is
D:/repository/junit/junit/4.11/junit-4.11.jar
now we can open it as JarFile and read it
JarFile jarFile = new JarFile(path);
...
I have a filename in my code as :
String NAME_OF_FILE="//sdcard//imageq.png";
FileInputStream fis =this.openFileInput(NAME_OF_FILE); // 2nd line
I get an error on 2nd line :
05-11 16:49:06.355: ERROR/AndroidRuntime(4570): Caused by: java.lang.IllegalArgumentException: File //sdcard//imageq.png contains a path separator
I tried this format also:
String NAME_OF_FILE="/sdcard/imageq.png";
The solution is:
FileInputStream fis = new FileInputStream (new File(NAME_OF_FILE)); // 2nd line
The openFileInput method doesn't accept path separators.
Don't forget to
fis.close();
at the end.
This method opens a file in the private data area of the application. You cannot open any files in subdirectories in this area or from entirely other areas using this method. So use the constructor of the FileInputStream directly to pass the path with a directory in it.
openFileInput() doesn't accept paths, only a file name
if you want to access a path, use File file = new File(path) and corresponding FileInputStream
I got the above error message while trying to access a file from Internal Storage using openFileInput("/Dir/data.txt") method with subdirectory Dir.
You cannot access sub-directories using the above method.
Try something like:
FileInputStream fIS = new FileInputStream (new File("/Dir/data.txt"));
You cannot use path with directory separators directly, but you will
have to make a file object for every directory.
NOTE: This code makes directories, yours may not need that...
File file= context.getFilesDir();
file.mkdir();
String[] array=filePath.split("/");
for(int t=0; t< array.length -1 ;t++)
{
file=new File(file,array[t]);
file.mkdir();
}
File f=new File(file,array[array.length-1]);
RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f,append);
String all = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String strLine;
while ((strLine = br.readLine()) != null){
all = all + strLine;
}
} catch (IOException e) {
Log.e("notes_err", e.getLocalizedMessage());
}
File file = context.getFilesDir();
file.mkdir();
String[] array = filePath.split("/");
for(int t = 0; t < array.length - 1; t++) {
file = new File(file, array[t]);
file.mkdir();
}
File f = new File(file,array[array.length- 1]);
RandomAccessFileOutputStream rvalue =
new RandomAccessFileOutputStream(f, append);
I solved this type of error by making a directory in the onCreate event, then accessing the directory by creating a new file object in a method that needs to do something such as save or retrieve a file in that directory, hope this helps!
public class MyClass {
private String state;
public File myFilename;
#Override
protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find
super.onCreate(savedInstanceState);
if (Environment.MEDIA_MOUNTED.equals(state)) {
myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory");
if (!myFilename.exists()) {
myFilename.mkdirs();
}
}
}
public void myMethod {
File fileTo = new File(myFilename.toString() + "/myPic.png");
// use fileTo object to save your file in your new directory that was created in the onCreate method
}
}
I did like this
var dir = File(app.filesDir, directoryName)
if(!dir.exists()){
currentCompanyFolder.mkdir()
}
var directory = app.getDir(directoryName, Context.MODE_PRIVATE)
val file = File(directory, fileName)
file.outputStream().use {
it.write(body.bytes())
}