我将字符串的长度写到文件中,结果是该值被视为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);}
}
}
答案 0 :(得分:0)
首先查看问题是否出在您写入文件的方式中
跟随此链接How To Read From A File In Java 并同时参见此链接How to Write Into A File in Java
问题不在Asci中,因为如果字符串的长度为int(应该是)
在将其写入文件
代替此行
fout.write(length);
写此行
fout.write(Integer.toString(length));
您可以在询问Stackoverflow之前先解决您的问题(它可以在Stackoverflow之前解决)
答案 1 :(得分:0)
您的代码将阅读与写作混合在一起-您同时拥有阅读对象和书写对象。由于您正在使用BufferedOutputStream
,因此输出不会直接写入文件(缓冲区未满时),并且在文件包含任何数据之前正在读取文件。
因此,要解决此问题,请在读取之前用fout.flush();
刷新输出流,或者最好将读取与写入分开:
import java.io.*;
class Fileoutput {
public static void main(String args[]) throws IOException {
File f = new File("test.txt");
f.createNewFile();
try (FileOutputStream fouts = new FileOutputStream(f); BufferedOutputStream fout = new BufferedOutputStream(fouts);) {
String s1 = "Good Afternoon have a nice day frghunv9uhbzsmk zvidzknmbnuf ofbdbmkxm;jccipx nc xdibnbnokcm knui9xkbmkl bv";
int length = s1.length();
System.out.println(length);
fout.write(length);
//fout.flush(); //optional, everything is flushed when fout is closed
System.out.println("Sucess");
}
try (FileInputStream fins = new FileInputStream(f); BufferedInputStream fin = new BufferedInputStream(fins);) {
int i;
while ((i = fin.read()) != -1) {
System.out.print((char) i);
}
System.out.println("All done");
}
}
}