如何使用netbeans IDE从硬盘驱动器的指定位置读取java文本文件中的内容



我有一个简单的程序,从使用netbeans IDE在java文本文件中读取内容。我想将位置指定为"D:/input.txt"。我怎么能做到呢?提前谢谢。

public class Abcd { 
 public static void main(String args[]) throws IOException 
 { 
 FileInputStream in = null; 
 FileOutputStream out = null; 
 try { 
 in = new FileInputStream("input.txt");   //specify exact location here.
 out = new FileOutputStream("output.txt"); 
 int c; 
 while ((c = in.read()) != -1) { 
 out.write(c); 
 } 
 }finally { 
 if (in != null) { 
 in.close(); 
 } 
 if (out != null) { 
 out.close(); 
 } 
 }} 
} 

可以直接指定完整路径:

in = new FileInputStream("D:\input.txt");  

为了避免不同操作系统之间的不兼容,您可以使用file.separator:

String sep = System.getProperty("file.separator");
//...
in = new FileInputStream("E:" + sep + "input.txt");

从Java 7开始,你可以使用try with resource,这样就不需要在finally循环中手动关闭流了

public class Abcd { 
 public static void main(String args[]) throws IOException 
 { 
 FileInputStream in = null; 
 FileOutputStream out = null; 
 try ( in = new FileInputStream("D:/input.txt");  
 out = new FileOutputStream("output.txt");){ 

 int c; 
 while ((c = in.read()) != -1) { 
 out.write(c); 
 } 
 }} 
} 

注意未测试代码

这是处理Exception可以升为IOException, FileNotFoundException的工作示例

public static void main(String[] args) {
    FileInputStream in = null; 
     FileOutputStream out = null; 
     try { 
         in = new FileInputStream("D:\input.txt");   //specify exact location here.
         out = new FileOutputStream("D:\output.txt"); 
         int c; 
         while ((c = in.read()) != -1) {                 
             out.write(c); 
         } 
     } catch(FileNotFoundException fe) {
        fe.printStackTrace();
     } catch(IOException ie) {
            ie.printStackTrace();
     } finally { 
         if (in != null) { 
             try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            } 
         } 
         if (out != null) { 
             try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } 
         } 
     }
}
public static void main(String[] args) {
        BufferedReader br = null;
        try {
            String sCurrentLine;
            br = new BufferedReader(new FileReader("D:\input.txt"));
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

相关内容

  • 没有找到相关文章