繁体   English   中英

获取.txt文件并用换行或逗号解析

[英]Get .txt file and parse it by new line or comma

我有一个.txt文件,格式如下:

file.txt(每行包含文本)

text1
text2
longtext3
...
..

我贬低它:

URL url = new URL(FILE_URL);

                    URLConnection connection = url.openConnection();
                    connection.connect();


                    // download the file
                    InputStream input = newBufferedInputStream(connection.getInputStream());

如何解析此input以便在每一行中获取文本?

我尝试过这样的事情:

BufferedReader br = new BufferedReader(new FileReader(file));  
                        String line;   
                        while ((line = br.readLine()) != null) {

                                    LIST.add(line);

                                    } }

但我不想保存它,所以我没有File实例

我可以以这种格式保存:

text1,text2,longtext3,....

如果提取起来更简单

您可以使用InputStreamReader( http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html )。

将其放在InputStream和BufferedReader之间。 现在,您不需要File实例(因此无需先保存它)。

就像是 ...

InputStream input = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = br.readLine()) != null) {

    LIST.add(line);

    // further break the line into a list of comma separated values
    List<String> commaSeparatedValues = Arrays.asList(line.split(","));
}
...

您可以使用Scanner

String result = "";

Scanner in = new Scanner(new FileInputStream(file));

while(in.hasNextLine())
    result += in.nextLine() + ",";

这将创建一个像这样的字符串:

text1,text2,longtext3,....

我不确定您要问什么,但我想您想保存文本文件的每一行。 这对我有用,它将每一行都放在一个长字符串中。

public static void main( String[] args ) 
{
    String FILE_URL = "http://www.google.com/robots.txt";
    String FILE_CONTENTS = "";
    try 
    {
        URL url = new URL(FILE_URL);

        URLConnection connection = url.openConnection();
        connection.connect();


        // download the file
        BufferedInputStream input = new BufferedInputStream(connection.getInputStream());   

        BufferedReader reader = new BufferedReader(new InputStreamReader(input));

        String line = reader.readLine();
        while( line != null ) 
        {
            FILE_CONTENTS += line;
            line = reader.readLine();
        }
    }
    catch( MalformedURLException e ) 
    {
        System.out.println("Malformed URL" );
    }
    catch( IOException e )
    {
        System.out.println( "IOException" );
    }
}

尝试扫描为普通文本并替换逗号中的每个'\\ n'...

暂无
暂无

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

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