Hello,
Please tell me what is the problem with my code:in the following code i try to create a directory.
Printable View
also, I have a proble with the following code
first file:
Code java:import java.io.*; public class OnlyExt implements FilenameFilter { String ext; public void OnlyExt(String ext) { this.ext="." + ext; } public boolean accept(File dir, String name) { return name.endsWith(ext); } }
second file:
in the following code i try to display the contents of a txt file using FileInputStream, and the output is
?
?
892745528
14
which is absolutely different from the contents of the txt file.
Code :import java.io.*; public class InputStream1 { public static void main (String[] args) { String path="d:/t.txt";// the file contains 123456789 //abcd //08 //9 try { FileInputStream fis=new FileInputStream(path); DataInputStream dis=new DataInputStream(fis); System.out.println (dis.readChar()); System.out.println (dis.readChar()); System.out.println (dis.readInt()); System.out.println (dis.available()); dis.close(); } catch(FileNotFoundException fe) { System.out.println("FileNotFoundException : " + fe); } catch(IOException ioe) { System.out.println("IOException : " + ioe); } } }
it looks like you're trying to read text. The best way to read text in is to not use the DataInputStream, but rather a BufferedReader or a Scanner object. These read text data rather than the raw bytes of the file.
thanx
but can u tell me
1-why we must use try and catch when dealing with files??
2-how to create a directory "see the first post"
When dealing with files, Java could possibly throw an IOException when the file couldn't be read/written to. There could be many reasons for this. IOException is a checked exception, i.e. you must always catch it (or alternatively you can propagate the exception up, though generally you shouldn't propagate exceptions out of your application).
It looks like you're trying to create a directory in a write-protected region (I'm assuming you're using Windows Vista or 7). The only solution is to launch your program with administrative rights, or to change where you're trying to create the directory in. Launching Java applications with administrative rights is particularly tricky, as you need to start the JVM with administrative rights.
If you're running your program from the command-line, you can start the command prompt with administrative rights, or set the JVM to always start with administrative rights (note: this is not recommended).
To add to helloworld's advice:
Code :File f1; f1.mkdir("c:/rr");
f1 was never instantiated == NullPointerException (did you see this exception when running this SSCCE?) First instantiate the file object, then call mkdir (and see the API for file...mkdir returns a boolean value as to whether the folder was created or not)
Code :File myDirectory = new File("my pile path"); if (!myDirectory.mkdir()){ //I could not create the directory }