简体   繁体   English

如何以相反的顺序获取输入流的内容?

[英]How to get the content of an input stream in reverse order?

I am using a txt file for my level desing. 我正在为自己的关卡设计使用txt文件。 I use the below to take the contents and convert to string buffer, then iterate through the lines to generate my game objects. 我使用以下内容获取内容并将其转换为字符串缓冲区,然后遍历各行以生成我的游戏对象。

The the problem is that it reads from top down and so I have to design my levels upside down for them to be right way around. 问题是它从上到下读取,因此我必须上下颠倒地设计水平,以使它们正确定位。

How can I change the stream to read the opposite way? 如何更改流以相反的方式阅读? Or write the lines to the String Builder the opposite way? 还是以相反的方式将这些行写入String Builder?

 private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            Log.w("LOG", e.getMessage());
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                Log.w("LOG", e.getMessage());
            }
        }
        return sb.toString();

You could just use sb.insert(0, line + "\\n") instead of sb.append(line + "\\n"); 您可以只使用sb.insert(0, line + "\\n")而不是sb.append(line + "\\n"); .

This will always add new lines to the front of the string, not append it to the end. 这将始终在字符串的开头添加新行,而不是将其附加到末尾。 Should do exactly what you want and will be just as fast, because StringBuilder is made exactly for things like that. 应该完全按照您想要的去做,并且速度会一样快,因为StringBuilder正是针对此类事情而制作的。

The only option you have to do that is with seek() function... 您要做的唯一选择是使用seek()函数...

I believe that is a solution, but the one you use will be far more easier... 我相信这是一种解决方案,但是您使用的解决方案会容易得多...

Here is an example of how to use seek: 这是如何使用查找的示例:

http://mark.koli.ch/2010/01/java-jumptoline-jump-to-a-line-in-a-file.html http://mark.koli.ch/2010/01/java-jumptoline-jump-to-a-line-in-a-file.html

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

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