如何将字符串的长度打印到文件

时间:2018-09-05 10:39:33

标签: java

在此程序中,我想在外部文件中打印字符串的长度,但问题是它使字符串中的字符数为字符的十进制值,并打印与ascii值匹配的字符并打印在一个文件中。

import java.io.FileOutputStream;
        class Fileoutputstream
        {
            public static void main(String args[])
            {
                try
                {
                    FileOutputStream foul=new FileOutputStream("/root/Documents/YG2108/DemoFiles.txt");
                    String s="hello Sir ";
                    String s1;
                    byte by[]=s.getBytes();
                    foul.write(by);
                    s1="Good Afternoon have a nice day frghunv9uhbzsmk zvidzknmbnuf ofbdbmkxm;jccipx nc     xdibnbnokcm knui9xkbmkl bv";
                    by=s.getBytes();
                    int yb=s.length();
                    int ascii = yb;     
                    foul.write(ascii);

                    System.out.println("Sucess");
                }catch(Exception e){System.out.println(e);}     
            }
        }

1 个答案:

答案 0 :(得分:0)

假设您要在DemoFiles.txt中写入字符串s1的length()

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

         File file=new File("C:\\Users\\1201567\\Desktop\\test.txt");

         BufferedWriter bf=new BufferedWriter(new FileWriter(file));

         String s1="Good Afternoon have a nice day frghunv9uhbzsmk zvidzknmbnuf ofbdbmkxm;jccipx nc     xdibnbnokcm knui9xkbmkl bv";

         int length=s1.length();

         bf.write(String.valueOf(length));
         bf.flush();
         System.out.println("Sucess");
     }catch(Exception e){System.out.println(e);}     
        }
    }