Correct way of accessing a file with name - java

Ok I need someone to clear things up for me.
I saw a hundred different ways of accessing a file to read in it (FileReader).
I tried all of them and can't find a way to do it correctly.
If I try :
String path = Engine.class.getResource("Words.txt").toString();
or
URL url = getClass().getResource("Words.txt");
String path = url.getFile();
File myFile = new File(path);
I go directly to :
dispatchUncaughtException
I just don't know where to look anymore since no one seems to agree on the good way to do it. Also, what is that kind of exception ?There must be an easy way to do this since it is such an easy task. I just want my program to see my Words.txt file that is in the SRC folder of my project.
Full code if it helps :
public String GetWord()
{
String [] Words = new String [10];
int random = (int)(Math.random() * 10);
URL url = getClass().getResource("Words.txt");
String path = url.getFile();
File myFile = new File(path);
try
{
FileReader myReader = new FileReader(myFile);
BufferedReader textReader = new BufferedReader(myReader);
for(int i = 0; i < 10; i++)
{
Words[i] = textReader.readLine();
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return Words[random];
}

String path = Engine.class.getResource("Words.txt").toString();
For that to work, your file has to be in the same package as the Engine class. So, you probably want to move your file to the package where the class is at.
If you want to move the file into some other package then you need to specify the location starting from the root of the classpath. e.g. /some/other/pkg/Words.txt.
For a file which is not in the classpath, you need the full path along with the file name, to be able to read the file. The SRC folder itself is not a package and not in the classpath.
In that case, you can do something as follows:
FileInputStream fis = new FileInputStream("C:\\path\\to\\file\\Words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));

If you use Java 7 I recommend using newBufferedReader. It's more efficient and easier to use than the BufferedReader. I also modified your code to match the Java Code Conventions.
Working exmaple:
public String getWord() {
String[] words = new String[10];
int random = (int) (Math.random() * 10);
Path path = Paths.get("src" + System.getProperty("file.separator")
+ "Words.txt");
try {
BufferedReader textReader = Files.newBufferedReader(path,
StandardCharsets.UTF_8);
for (int i = 0; i < 10; i++) {
words[i] = textReader.readLine();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return words[random];
}

Related

How to get the updated file text

I am making a JFrame from where the user will be able to insert new methods in the file. If the file is not there, program will create the new file and then insert the method there. If the file is already there, it will try to create the new method with the given name but if the file contains the method with the same name, it'll give user the alert.
I am able to do all these things properly, only problem is after creating the new method in the class file, if the user again click on the Create Method button, application does not throws any alert as it is unable to read the new method name from the file. When I check the file content, I can see the new method there but somehow my code is not able to read the new code from the file. Here is the code for the same.
File f = null;
f = new File(Report.path + "//src//_TestCases//" + tc_name + ".java");
if (!f.exists()) {
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
f.createNewFile();
bw.write(testcase);
bw.close();
}
Class<?> c = Class.forName("_TestCases." + tc_name);
Method[] m = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().toLowerCase()
.equals(module_name.toLowerCase())) {
JOptionPane
.showMessageDialog(null,
"Module with the given name already exists. Please provide other name.");
return false;
}
}
List<String> lines = Files.readAllLines(f.toPath(),
StandardCharsets.UTF_8);
String text = "";
if (lines.contains(" #AfterClass")) {
text = " #AfterClass";
} else {
text = "#AfterClass";
}
lines.add(lines.indexOf(text), "#Test\npublic void " + module_name
+ "() throws Exception {\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
for (int i = 0; i < tc_values.size(); i++) {
lines.add(lines.indexOf(text), tc_values.get(i));
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
}
lines.add(lines.indexOf(text), "\n}\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
Not sure what the issue was but when I changed the logic of getting the method name from the file, it worked for me. Used scanner to read the file contents and get the method name, earlier was using the below line to get the method name from the file.
Method[] m = c.getDeclaredMethods();

Java Filenotfound exception being thrown

A FileNotFound Exception is being thrown for my code even though I have the file in the exact directory I stated. I have also tried ...new File("euler8.txt");... with no success. My code is as follows:
private static void euler8() throws IOException
{
int current;
int largest=0;
int c =0;
ArrayList<Integer> bar = new ArrayList<Integer>(0);
File infile = new File("C:/Users/xxxxxxxx/workspace/Euler1/euler8.txt");
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(infile),
Charset.forName("UTF-8")));
try
{
while((c = reader.read()) != -1)
{
bar.add(c);
}
}
finally{reader.close();}
for(int i=0; i<bar.size(); i++)
{
current = bar.get(i) * bar.get(i+1) * bar.get(i+2) * bar.get(i+3) * bar.get(i+4);
if(largest<current)
largest = current;
}
}
Image of what it is doing:
http://img163.imageshack.us/img163/7017/halpbk.png
Except for everything else that has been suggested, you could check whether you're having this issue (which we've been seeing in our lab): Files with twice the extension. In other words, make sure your euler8.txt is really called that and not euler8.txt.txt, for instance, because, with hidden extensions, the file explorer will show the first but it may not strike you as odd initially, if you don't remember that it's supposed to hide the extension.
Forward slashes work fine, and are preferred because they work on any platform (relative paths are better than absolute). Make sure your path exists as specified, and verify that you have read access on the directories leading to the file. For example, if you're running your java program as a different user, you may not have read access on the "myuser" folder.
This code will not work if all of the directories do not yet exist as well, so I'd assume (hopefully I am correct) that you have a typo, or are missing a folder.
I usually prefer to have a java.io.File reference to the parent directory, then use it as parent in a subsequent file reference, i.e.:
File dir = new File("parentDir");
File inFile = new File(dir, "fileName");
Also, java.io.File has an exists() method that returns true or false, and its subsequent mkdir(),mkdirs(), and createNewFile() return true or false if they actually create the requested file.
That said, I modified your code to the following, and it executes on my machine; but I do not know what data you are trying to run through this.
int current;
int largest = 0;
int c = 0;
ArrayList<Integer> bar = new ArrayList<Integer>(0);
File dir = new File("C:/Users/myuser/workspace/Euler1");
if(!dir.exists()){
dir.mkdirs();
}
File infile = new File(dir, "euler8.txt");
if(!infile.exists()){
infile.createNewFile();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(infile),
Charset.forName("UTF-8")));
try {
while ((c = reader.read()) != -1) {
bar.add(c);
}
} finally {
reader.close();
}
for (int i = 0; i < bar.size(); i++) {
current = bar.get(i) * bar.get(i + 1) * bar.get(i + 2) * bar.get(i + 3) * bar.get(i + 4);
if (largest < current) {
largest = current;
}
}
The backslashes are quite unnecessary. I ran this program:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class Test {
public static void main(String[] args) throws IOException {
File infile = new File("C:/Users/pats/workspace/test/euler8.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(infile), Charset.forName("UTF-8")));
try {
String s;
while ((s = reader.readLine()) != null) {
System.out.println(s);
}
} finally {
reader.close();
}
}
}
which is very similar, and it printed the contents of my file.
I think you need to check both that the file exists, and that you have access to it.

Java project can't find file

I have a project that finds a text file and makes it into an array of characters. However, for some reason or another it isn't finding the file. This is all the code involving opening/reading the file:
public void initialize(){
try{
File file = new File(getClass().getResource("/worlds/world1.txt").toString());
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
for(int i = 0; (c = reader.read()) != -1; i ++) {
for(int x = 0; x < 20; x++){
worlds[1][x][i] = (char) c;
c = reader.read();
}
}
}catch(IOException e){
e.printStackTrace();
}
}
When ran, it shows in the console that it is pointing to the correct file, but claims nothing exists there. I've checked, and the file is completely intact and in existence. What could be going wrong here?
You should not get a resource like that. You can use
BufferedReader reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream("/worlds/world1.txt")
));
Also, be careful when you package your application if you develop it inside an IDE, otherwise you'll run into common CLASSPATH troubles
File path for embedded resources is calculated from the package root folder. Assuming that src folder is the root package folder, make sure, that world1.txt file is located at src/worlds/ folder and full path is src/worlds/world1.txt
Second point, use the following code to obtain embedded file reader object:
// we do not need this line anymore
// File file = new File(getClass().getResource("/worlds/world1.txt").toString());
// use this approach
BufferedReader reader = new BufferedReader(
new InputStreamReader(
getClass().getResourceAsStream("/worlds/world1.txt"),
Charset.forName("UTF-8")));
You haven't indicated where your file lives.
getClass().getResource is used to locate a resource/file on your classpath; the resource may be packaged in your jar, for example. In this case, you can't open it as a File; see Raffaele's response.
If you want to locate the resource/file on the file system, then create the File object directly without getResource():
new File("/worlds/world1.txt")
I was using Netbeans and I was getting similar results. When I defined the file Path from the C drive and ran my code it stated: Access has been denied.
The following code ran fine, just back track your file location to the source (src) file.
//EXAMPLE FILE PATH
String filePath = "src\\solitaire\\key.data";
try {
BufferedReader lineReader = new BufferedReader(new FileReader(filePath));
String lineText = null;
while ((lineText = lineReader.readLine()) != null) {
hand.add(lineText);
System.out.println(lineText); // Test print of the lines
}
lineReader.close(); // Closes the bufferReader
System.out.print(hand); // Test print of the Array list
} catch(IOException ex) {
System.out.println(ex);
}

URL and readbuffer won't export

I have a huge program that I have spent 100+ hours on. It would not work when I exported it even though it worked fine in Ecipse. I made a smaller program with just that code to test it out. I have searched and changed my code and I still can't get my program to work when I export and run my jar file. It works great in Eclipse. I have tried file reader, stream, buffer, standing on my head, and changed to anything I have seen online about reading a file that is included in the jar file. I am new to coding so some things still confuse me. I changed the .java to .zip and looked at the pieces and the file is in there.
My read code is
private void readFile(){
try {
System.out.println("starting array");
String[] myarray;
myarray = new String[5];
System.out.println("myarray"+myarray);
url = getClass().getResource("classifyinginfo.txt");
System.out.println("url is "+url);
readbuffer = new BufferedReader(new FileReader(url.getPath()));
line1 = readbuffer.readLine();
line1 = readbuffer.readLine();
line1 = readbuffer.readLine();
line1 = readbuffer.readLine();
{ String splitarray[] = line1.split(",");
firstentry = splitarray[0];
myarray[0]=splitarray[3];
myarray[1]=splitarray[4];
myarray[2]=splitarray[5];
myarray[3]=splitarray[6];
myarray[4]=splitarray[7];
//line2 and 3 readbuffer etc
Arrays.sort(myarray);
for(int i=0; i < myarray.length; i++){
System.out.println(myarray[i]);
textArea.append(myarray[i]+"\n");}
}
System.out.println(Arrays.toString(myarray));
// textArea.setText(Arrays.toString(myarray));
readbuffer.close(); } catch (IOException e) {
System.out.println("we have an error");}
System.out.println("Line: " + line1 );
}
please please tell me how to make this work in and out of Eclipse.
You just do like this:
url = getClass().getResource("classifyinginfo.txt");
readbuffer = new BufferedReader(new InputStreamReader(url.openStream()));
line1 = readbuffer.readLine();
The FileReader class can read individual files on disk, and that's all. But you don't need to use it once you have a URL. Modified in this way, the program will work whether the file is in a jar or not.
You can actually eliminate the URL altogether and just do this:
readbuffer =
new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("classifyinginfo.txt")));
line1 = readbuffer.readLine();

Are these two ways of creating files, the same?

I was writing a program in Java to search for a piece of text
I took these 3 as inputs
The directory, from where the search should start
The text to be searched for
Should the search must be recursive (to or not to include the directories inside a directory)
Here is my code
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File file = new File(dirToSearch);
String[] fileNames = file.list();
for(int j=0; j<fileNames.length; j++)
{
File anotherFile = new File(fileNames[j]);
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
When recursion is set true, the program returns a FILENOTFOUNDEXCEPTION
So, I referred to the site from where I got the idea to implement this program and edited my program a bit. This is how it goes
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File[] files = new File(dirToSearch).listFiles();
for(int j=0; j<files.length; j++)
{
File anotherFile = files[j];
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
It worked perfectly then. The only difference between the two snippets is the way of creating the files, but they look the same to me!!
Can anyone point me out where I messed up?
In the second example it is used listFiles() whichs returns files. In your example it is used list() which returns only the names of the files - here the error.
The problem in the first example is in the fact that file.list() returns an array of file NAMES, not paths. If you want to fix it, simply pass file as an argument when creating the file, so that it's used as the parent file:
File anotherFile = new File(file, fileNames[j]);
Now it assumes that anotherFile is in the directory represented by file, which should work.
You need to include the base directory when you build the File object as #fivedigit points out.
File dir = new File(dirToSearch);
for(String fileName : file.list()) {
File anotherDirAndFile = new File(dir, fileName);
I would close your files when you are finished and I would avoid using throws Exception.

Categories

Resources