有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    假设要在DemoFile中写入字符串s1的长度()。文本

    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);}     
            }
        }