Java:将文件内容读取并输出为字节格式

时间:2014-04-11 05:18:01

标签: java

我今天早些时候在这里发布了一个类似的问题,我知道我不应该在这里问HW问题。我的问题是作业,但它已经完成并提交(和评分),我在这里希望能让我的程序更好地运行:)

为了表明我已经完成了它并且没有试图快速推送它,这里有一个指向提交页面的链接:http://i959.photobucket.com/albums/ae76/GoWxGaiA/SOHW2pic_zps25eb2d2a.jpg

说明就在这里:http://i959.photobucket.com/albums/ae76/GoWxGaiA/pic3_zpsbb6c6541.png

这是我到目前为止所提交的内容:

package Homework1;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    public class HW1 {
        public static void main(String[] args){
            System.out.println("Enter a file name:                         c:/users/logan/desktop/untitled.png");
        System.out.println("Byte#     Byte\n0:        255\n1:        216\n2:        255\n3:        244\n4:        0\n5:        16\n6:        74\n7:        70\n8:        73");      
   File file = new File("C://Users//Logan//Desktop//Untitled.png");   
   try
        {
          FileInputStream fin = new FileInputStream(file);     
          byte fileContent[] = new byte[(int)file.length()];

   fin.read(fileContent);
   String strFileContent = new String(fileContent);     
   System.out.println("File content : ");
   System.out.println(strFileContent);
     }
    catch(FileNotFoundException e)    {
  System.out.println("File not found" + e);    }
catch(IOException ioe)    {
  System.out.println("Exception while reading the file " + ioe);    }
  }
}

所以我的问题是:

问题1:如何提示用户输入文件名而不是硬编码?

问题2:如何使用循环显示每个字节值?

所有和任何帮助都非常有价值!

1 个答案:

答案 0 :(得分:1)

要提示某人输入,请考虑使用Scanner类

System.out.print("Please enter file path and name: ");
String input = scan.nextLine();

循环逐字节inputStream.read()方法 见http://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html#read()

while ((ch = fis.read ()) != -1) {
   System.out.print(ch);
}