开发者

Having trouble opening a file in Java

I am trying to open this file in java and i want to know what i am doing wrong. The in file lies in the same directory as my Java file, but i tried to open this with both netbeans and eclipse and it gave a file not found exception. Can someone help me open this file and read from it. I am really new to java files. Here is the code

 import java.util.*;
    import java.io.*;

    public class Practice
    {

      public static void main(String[] args)throws IOException
      {


          FileReader fin = new FileReader("anagrams.in");
          BufferedReader br = new BufferedReader(fin);



          System.out.println(fin);


        String string = "Madam Curie";
        String test = "Radium came";

        string = string.toLowerCase();
        test = test.toLowerCase();

        string = string.replaceAll("[^a-zA-Z0-9]+", "");
        test = test.replaceAll("[^a-zA-Z0-9]+", "");

        char[] array = string.toCharArray();
        char[] array2 = test.toCharArray();

        boolean flag = false;
        HashMap hm = new HashMap();


        for(int i = 0; i < array.length; i++)
        {
            hm.put(array[i], array[i]);
        }

       for(int i = 0; i < array2.length; i++)
       {
           if(hm.get(array2[i]) == null || test.length() != string.length())
           {
               flag = false;
               i = array2.length;
           }
           else
           {
               flag = true;
           }

       }

       System.out.println(flag);
      }
开发者_C百科
    }


A few tips:

  1. Abide to proper code indentation
    • If you're using an IDE like Eclipse, it can automatically correct indentation for you
  2. Develop debugging instinct
    • Try to get what the current working directory is, and list all the files in it
  3. Refactor repetitive code
    • Writing paired statements like you did should immediately raise red flags
  4. Effective Java 2nd Edition
    • Item 23: Don't use raw types in new code
    • Item 52: Refer to objects by their interfaces
    • Item 46: Prefer for-each loops to traditional for loops
  5. Use sensible variable names

With regards to 2, try something like this:

public static void listDir() {
    File current = new File(".");
    System.out.println(current.getAbsolutePath());
    for (String filename : current.list()) {
        System.out.println(filename);
    }
}

Then in your main, simply call listDir before everything else, and see if you're running the app from the right directory, and if there's a "anagrams.in" in the directory. Note that some platforms are case-sensitive.

With regards to 3 and 4, consider having a helper method like this:

static Set<Character> usedCharactersIn(String s) {
    Set<Character> set = new HashSet<Character>();
    for (char ch : s.toLowerCase().toCharArray()) {
        set.add(ch);
    }
    return set;
}

Note how Set<E> is used instead of Map<K,V>. Looking at the rest of the code, you didn't seem to actually need a mapping, but rather a set of some sort (but more on that later).

You can then have something like this in main, which makes the logic very readable:

    String s1 = ...;
    String s2 = ...;

    boolean isNotQuiteAnagram = (s1.length() == s2.length()) &&
        usedCharactersIn(s1).containsAll(usedCharactersIn(s2));

Note how variables are now named rather sensibly, highlighting their roles. Note also that this logic does not quite determine that s1 is an anagram of s2 (consider e.g. "abb" and "aab"), but this is in fact what you were doing.

Since this looks like homework, I'll leave it up to you to try to figure out when two strings are anagrams.

See also

  • Java Coding Conventions
  • Java Language Guide/For-each loop
  • Java Tutorials/Collections Framework

Related questions

  • Why doesn't Java Map extends Collection?


Make sure that the file lies in the same directory as your .class file. It doesn't matter if it is in the same as your .java file or not.

Other than that, the only problem I can see is in your indentation, which doesn't matter.


The normal practice is to put resources in the runtime classpath or to add its path to the runtime classpath so that you can get it by the classloader. Using relative paths in Java IO is considered poor practice since it breaks portability. The relative path would be dependent on the current working directory over which you have totally no control from inside the Java code.

After having placed it in the classpath (assuming that it's in the same folder as the Java class itself), just do so:

BufferedReader reader = null;

try {
    InputStream input = Practice.class.getResourceAsStream("anagrams.in");
    reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); // Or whatever encoding it is in.

    // Process it.
    // ...
} finally {
    if (reader != null) try { reader.close(); } catch (IOException ignore) {}
}

Closing in finally is by the way mandatory to release the lock on the file after reading.


Put the anagrams.in file in the same location as the .class file. Then you will be able to read the file. And this should help you get some links on how to read from files in Java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜