简体   繁体   English

将从文件读取的数据捕获到字符串流Java中

[英]Capture data read from file into string stream Java

I'm coming from a C++ background, so be kind on my n00bish queries... 我来自C ++背景,所以请对我的n00bish查询好一点...

I'd like to read data from an input file and store it in a stringstream. 我想从输入文件中读取数据并将其存储在stringstream中。 I can accomplish this in an easy way in C++ using stringstreams. 我可以使用stringstreams在C ++中以简单的方式完成此操作。 I'm a bit lost trying to do the same in Java. 我在Java中尝试做同样的事情有点迷失。

Following is a crude code/way I've developed where I'm storing the data read line-by-line in a string array. 以下是我开发的粗略代码/方式,其中将读取的数据逐行存储在字符串数组中。 I need to use a string stream to capture my data into (rather than use a string array).. Any help? 我需要使用字符串流将数据捕获到其中(而不是使用字符串数组)。有什么帮助吗?

    char dataCharArray[] = new char[2];
    int marker=0;
    String inputLine;
    String temp_to_write_data[] = new String[100];

    // Now, read from output_x into stringstream

    FileInputStream fstream = new FileInputStream("output_" + dataCharArray[0]);

    // Convert our input stream to a BufferedReader
    BufferedReader in = new BufferedReader (new InputStreamReader(fstream));

    // Continue to read lines while there are still some left to read
    while ((inputLine = in.readLine()) != null )
    {
        // Print file line to screen
        // System.out.println (inputLine);
        temp_to_write_data[marker] = inputLine;
        marker++;
    }

EDIT: 编辑:

I think what I really wanted was a StringBuffer. 我认为我真正想要的是一个StringBuffer。 I need to read data from a file (into a StringBuffer, probably) and write/transfer all the data back to another file. 我需要从文件中读取数据(可能是到StringBuffer中),然后将所有数据写/传输回另一个文件中。

In Java, first preference should always be given to buying code from the library houses: 在Java中,应始终优先考虑从图书馆购买代码:

http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html http://commons.apache.org/io/api-1.4/org/apache/commons/io /FileUtils.html

In short, what you need is this: 简而言之,您需要的是:

FileUtils.readFileToString(File file)

I also come from C++, and I was looking for a class similar to the C++ 'StringStreamReader', but I couldn't find it. 我也来自C ++,我一直在寻找与C ++'StringStreamReader'类似的类,但找不到。 In my case (which I think was very simple), I was trying to read a file line by line and then read a String and an Integer from each of these lines. 就我而言(我认为这很简单),我试图逐行读取文件,然后从每行读取一个String和一个Integer。 My final solution was to use two objects of the class java.util.Scanner, so that I could use one of them to read the lines of the file directly to a String and use the second one to re-read the content of each line (now in the String) to the variables (a new String and a positive 'int'). 我的最终解决方案是使用类java.util.Scanner的两个对象,以便可以使用其中一个将文件的行直接读取为String,并使用第二个对象重新读取每行的内容(现在在String中)到变量(新的String和一个正的'int')。 Here's my code: 这是我的代码:

try {
    //"path" is a String containing the path of the file we want to read
    Scanner sc = new Scanner(new BufferedReader(new FileReader(new File(path))));
    while (sc.hasNextLine()) { //while the file isn't over
        Scanner scLine = new Scanner(sc.nextLine());
        //sc.nextLine() returns the next line of the file into a String
        //scLine will now proceed to scan (i.e. analyze) the content of the string
        //and identify the string and the positive 'int' (what in C++ would be an 'unsigned int')
        String s = scLine.next(); //this returns the string wanted
        int x;
        if (!scLine.hasNextInt() || (x = scLine.nextInt()) < 0) return false;
        //scLine.hasNextInt() analyzes if the following pattern can be interpreted as an int
        //scLine.nextInt() reads the int, and then we check if it is positive or not
        //AT THIS POINT, WE ALREADY HAVE THE VARIABLES WANTED AND WE CAN DO
        //WHATEVER WE WANT WITH THEM
        //in my case, I put them into a HashMap called 'hm'
        hm.put(s, x);
    }
    sc.close();
    //we finally close the scanner to point out that we won't need it again 'till the next time
} catch (Exception e) {
    return false;
}
return true;

Hope that helped. 希望能有所帮助。

StringBuffer is one answer, but if you're just writing it to another file, then you can just open an OutputStream and write it directly out to the other file. StringBuffer是一个答案,但是如果您只是将其写入另一个文件,则可以打开一个OutputStream并将其直接写到另一个文件中。 Holding a whole file in memory is probably not a good idea. 在内存中保存整个文件可能不是一个好主意。

In you simply want to read a file and write another one: 在其中,您只想读取一个文件并编写另一个文件:

BufferedInputStream in = new BufferedInputStream( new FileInputStream( "in.txt" ) );
BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream( "out.txt" ) );
int b;
while ( (b = in.read()) != -1 ) {
    out.write( b );
}

If you want to read a file into a string: 如果要将文件读取为字符串:

StringWriter out = new StringWriter();
BufferedReader in = new BufferedReader( new FileReader( "in.txt" ) );
int c;
while ( (c = in.read()) != -1 ) {
    out.write( c );
}
StringBuffer buf = out.getBuffer();

This can be made more efficient if you read using byte arrays. 如果使用字节数组进行读取,则可以提高效率。 But I recommend that you use the excellent apache common-io. 但我建议您使用出色的Apache common-io。 IOUtils ( http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html ) will do the loop for you. IOUtils( http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html )将为您完成循环。

Also, you should remember to close the streams. 另外,您应该记得关闭流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM