java中的文件处理

发布于 2024-11-14 14:13:46 字数 785 浏览 1 评论 0原文

我有下面的代码。

下面的源代码来自文件 x.java。 hi.html 与 x.java 位于同一目录中。

即使文件存在,我也收到文件未找到异常。我错过了什么吗?

    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(Exception e){
        String errorMessage = "file not found";
        output.write(errorMessage.getBytes());
    }finally {
        if(fis != null){
            fis.close();
        }

    }

}

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(Exception e){
        String errorMessage = "file not found";
        output.write(errorMessage.getBytes());
    }finally {
        if(fis != null){
            fis.close();
        }

    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

亚希 2024-11-21 14:13:46

.java文件的目录不一定是你的代码运行的方向!您可以通过以下示例检查程序的当前工作目录:

 System.out.println( System.getProperty( "user.dir" ) );

您可以使用 System.getProperty( "user.dir" ) 字符串使相对文件名成为绝对文件名!只需将其添加到您的文件名前面即可:)

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 :)

煮酒 2024-11-21 14:13:46

查看您的“user.dir”属性。

String curDir = System.getProperty("user.dir");

程序将在此处开始搜索没有完整路径的文件。

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.

多像笑话 2024-11-21 14:13:46
  • 在捕获Exception之前先捕获FileNotFoundException,以确保这是真正的Exception类型。
  • 由于您没有给出文件的绝对位置,因此它会从您的工作目录中搜索。您可以将绝对路径存储在属性文件中并使用它,或者使用 System.getProperty("user.dir") 返回运行 Java 应用程序的目录。

从属性文件获取键值的代码

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();
    }
}
  • 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();
    }
}
记忆之渊 2024-11-21 14:13:46

我猜你会得到一个 NullPointerException:

FileInputStream fis = null;

然后调用:

int i = fis.available();

将导致一个 NullPointerException ,因为稍后对 fis 进行第一个非空赋值:

fis = new FileInputStream(file);

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);
凌乱心跳 2024-11-21 14:13:46
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
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
当梦初醒 2024-11-21 14:13:46
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");
}
}
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");
}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文