inputfilestream到String

时间:2013-07-08 16:51:51

标签: java

我有以下逻辑来打开文件:

除了我想要做的不仅仅是在屏幕上打印文件,而是采取一行并将其存储到名为test的字符串。

有人可以帮帮我吗?

// fetch the file
String filename = "companySecret.txt";
String filepath = "C:\\";
String test;

java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);

int i;

while ((i=fileInputStream.read()) != -1) 
{

    System.out.write(i);
}

fileInputStream.close();

3 个答案:

答案 0 :(得分:3)

我建议你使用BufferedReader类并使用ReadLine方法从文件中提取行。

// fetch the file
String filename = "companySecret.txt";
String filepath = "C:\\";
String test;

java.io.FileReader fileInputReader = new java.io.FileReader(filepath + filename);
java.io.BufferedReader input = new java.io.BufferedReader( fileInputReader );


while ((test=input.readLine()) != null) 
{
    // Do something with the line...
}

fileInputStream.close();

答案 1 :(得分:2)

使用Apache Commons IO library

String fileContents = FileUtils.readFileToString(file);

http://commons.apache.org/proper/commons-io/javadocs/api-2.4/index.html

答案 2 :(得分:0)

使用StringBuilder代替String

然后

 StringBuilder test=new StringBuilder();

然后在你的while循环中

  test.append("your String");

或者您可以按照以下方式使用String

 String test=new String();

  test +=your_String;

试试这个

   Scanner sc=new Scanner(new FileReader("D:\\Test.txt"));
   StringBuilder test=new StringBuilder();
   String str;
   while (sc.hasNext()){
       str=sc.next();
       System.out.println(str);
       test.append(str);
   }

阅读特定行

   import java.io.BufferedReader;
   import java.io.FileReader;
   import java.io.IOException;
   public class Read {
   public static void main(String[] args) throws IOException {
   FileReader fr=new FileReader("D:\\Test.txt");
   BufferedReader br=new BufferedReader(fr);
   StringBuilder test=new StringBuilder();
   String str;
   int count=1;
   while ((str=br.readLine())!=null){
       if(count==1){
           System.out.println(str);
           test.append(str);
       }
         count++;
   }
}
}