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

发布于 2024-08-26 19:38:15 字数 1013 浏览 3 评论 0原文

我来自 C++ 背景,所以请善待我的 n00bish 查询...

我想从输入文件中读取数据并将其存储在字符串流中。我可以使用字符串流在 C++ 中以简单的方式完成此任务。我在尝试用 Java 做同样的事情时有点迷失。

以下是我开发的粗略代码/方式,我将逐行读取的数据存储在字符串数组中。我需要使用字符串流将数据捕获到(而不是使用字符串数组).. 有帮助吗?

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

编辑:

我认为我真正想要的是 StringBuffer。 我需要从文件中读取数据(可能读取到 StringBuffer 中)并将所有数据写入/传输回另一个文件。

I'm coming from a C++ background, so be kind on my n00bish queries...

I'd like to read data from an input file and store it in a stringstream. I can accomplish this in an easy way in C++ using stringstreams. I'm a bit lost trying to do the same in 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.
I need to read data from a file (into a StringBuffer, probably) and write/transfer all the data back to another file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

樱花细雨 2024-09-02 19:38:15

在 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

简而言之,您需要的是这样的:

FileUtils.readFileToString(File file)

In Java, first preference should always be given to buying code from the library houses:

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)
苏璃陌 2024-09-02 19:38:15

StringBuffer 是一个答案,但如果您只是将其写入另一个文件,那么您可以打开一个 OutputStream 并将其直接写入另一个文件。将整个文件保存在内存中可能不是一个好主意。

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. Holding a whole file in memory is probably not a good idea.

命比纸薄 2024-09-02 19:38:15

如果您只想读取一个文件并写入另一个文件:

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

如果您想将一个文件读入字符串:

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

如果您使用字节数组进行读取,则可以提高效率。但我建议你使用优秀的apache common-io。 IOUtils (http://commons.apache. org/io/api-1.4/org/apache/commons/io/IOUtils.html)将为您执行循环。

另外,您应该记住关闭流。

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. IOUtils (http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html) will do the loop for you.

Also, you should remember to close the streams.

心如狂蝶 2024-09-02 19:38:15

我也来自C++,我一直在寻找类似于C++“StringStreamReader”的类,但我找不到它。就我而言(我认为非常简单),我尝试逐行读取文件,然后从每一行读取一个字符串和一个整数。我的最终解决方案是使用 java.util.Scanner 类的两个对象,这样我就可以使用其中一个对象将文件的行直接读取到字符串,并使用第二个对象重新读取每一行的内容(现在在字符串中)到变量(一个新的字符串和一个正的“int”)。这是我的代码:

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;

希望有帮助。

I also come from C++, and I was looking for a class similar to the C++ 'StringStreamReader', but I couldn't find it. 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. 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'). 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文