File handling in java
I have the below code.
The below source code is from the file x.java. The hi.html is present in the same directory as x.java.
I get a file not found exception even though the file is present. Am I missing something ?
public void sendStaticResource() throws IOException{
byte[] bytes = new byte[1024];
FileInputStream fis = null;
try{
File file = new File("hi.html");
boolean p = file.exists();
int i = fis.available();
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, 1024);
while(ch!=-1){
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, 1024);
}
}catch(Except开发者_开发技巧ion e){
String errorMessage = "file not found";
output.write(errorMessage.getBytes());
}finally {
if(fis != null){
fis.close();
}
}
}
The directory of the .java file is not necessarily the direction your code runs in! You can check the current working dir of your program by in example:
System.out.println( System.getProperty( "user.dir" ) );
You could use the System.getProperty( "user.dir" ) string to make your relative filename an absolute one! Just prefix it to your filename :)
Take a look at your "user.dir" property.
String curDir = System.getProperty("user.dir");
That's where the program will root its search for files that don't have a complete path.
- Catch the FileNotFoundException before catching Exception so as to be sure that is the real Exception type.
- Since you don't give an absolute location for a file it searches from your working directory. You can store the absolute path in a property file and use that instead or use
System.getProperty("user.dir")
to return the directory that you are running the Java app from.
Code to get Key-Value from Property files
private void getPropertyFileValues() {
String currentPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "Loader.properties";
FileInputStream fis = null;
try {
fis = new FileInputStream(currentPath);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
Properties props = new Properties();
try {
props.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
String filePath= props.getProperty("FILE_PATH");
try {
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
I guess you get a NullPointerException
:
FileInputStream fis = null;
then the call:
int i = fis.available();
will result in an NullPointerException
as the first non-null assignment to fis
is later:
fis = new FileInputStream(file);
File Handling in Java:
Use File class for Representing and manipulating file or folder/directory.
you can use constructor :
ex. File file = new File("path/file_name.txt");
or
File file = new File("Path","file_name");
File representation example:
import java.io.File;
import java.util.Date;
import java.io.*;
import java.util.*;
public class FileRepresentation {
public static void main(String[] args) {
File f =new File("path/file_name.txt");
if(f.exists()){
System.out.println("Name " + f.getName());
System.out.println("Absolute path: " +f.getAbsolutePath());
System.out.println("Is writable " +f.canWrite());
System.out.println("Is readable " + f.canRead());
System.out.println("Is File " + f.isFile());
System.out.println("Is Directory " + f.isDirectory());
System.out.println("Last Modified at " + new Date(f.lastModified()));
System.out.println("Length " + f.length() +"bytes long.");
}//if
}//main
}//class
Write data character by character, into Text file by Java:
use FileWriter Class-
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class WriteFile {
public static void main(String[] args) throws Exception{
//File writer takes chars and convert into bytes and write to a file
FileWriter writer = new FileWriter("path/file_name.txt");
//if file not exits then created it, else override data
writer.write('A');
writer.write('E');
writer.write('I');
writer.write('O');
writer.write('U');
writer.close();
System.out.println("Successfully Written");
}
}
精彩评论