首页 > 解决方案 > 打印文件内容的问题

问题描述

我正在将字符串的长度写入文件,结果是该值被视为 ASCII 值,并且用 ASCII 值指定的字符被写入文件中,然后我尝试在 FileInputStream 的帮助下读取该字符和BufferInputStream 和结果不会显示在控制台上。为什么文件中的字符没有打印到控制台?

import java.io.*;
class Fileoutput{
    public static void main(String args[])
    {
        try
        {

         File f=new File("C:\\Users\\parsh\\YG2108\\Testfile.txt");
         FileInputStream fins=new FileInputStream("C:\\Users\\parsh\\YG2108\\Testfile.txt");
         FileOutputStream fouts=new FileOutputStream("C:\\Users\\parsh\\YG2108\\Testfile.txt");
         FileWriter bf=new FileWriter("C:\\Users\\parsh\\YG2108\\Testfile.txt");
         BufferedInputStream fin=new BufferedInputStream(fins);
         BufferedOutputStream fout=new BufferedOutputStream(fouts);
         BufferedWriter bw=new BufferedWriter(bf);
         int i;
         String s1="Good Afternoon have a nice day frghunv9uhbzsmk zvidzknmbnuf ofbdbmkxm;jccipx nc     xdibnbnokcm knui9xkbmkl bv";

         int length=s1.length();           //findin string length
         System.out.println(length);       //printing length on console
         fout.write(length);               //writting into the file
         System.out.println("Sucess");
         while((i=fin.read())!=-1)
         {    
             System.out.print((char)i);    
         }    
         bw.close();
         fout.close();
         fin.close();
         bf.close();
         fouts.close();
         fins.close();
         System.out.println("All done");
        }catch(Exception e){System.out.println(e);}     
    }
}

标签: javafile-io

解决方案


首先看看问题是否出在你写入文件的方式上
按照这个链接 How To Read From A File In Java and See this Link 如何在Java中写入文件 问题不在Asci中,因为如果字符串是 int (应该是),您应该在将其写入文件之前使用 Integer.tostring(length_of_the_string) 解析它

而不是这条线

fout.write(length);   

写下这一行

fout.write(Integer.toString(length)); 

在 Stackoverflow 上提问之前,您可以谷歌搜索您的问题(在 Stackoverflow 之前可能已解决)


推荐阅读