Java 获取.txt文件并用新行或逗号对其进行解析
我有一个.txt文件,格式如下:Java 获取.txt文件并用新行或逗号对其进行解析,java,android,Java,Android,我有一个.txt文件,格式如下: text1,text2,longtext3,.... file.txt(每行有文本) 我在往下说: URL url = new URL(FILE_URL); URLConnection connection = url.openConnection(); connection.connect(); // download the fil
text1,text2,longtext3,....
file.txt(每行有文本)
我在往下说:
URL url = new URL(FILE_URL);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream input = newBufferedInputStream(connection.getInputStream());
我如何解析这个输入
,从而获得每一行的文本
我试过这样的方法:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
LIST.add(line);
} }
但是我不想保存它,所以我没有文件
实例
我可以用以下格式保存:
text1,text2,longtext3,....
如果提取它更简单,您可以使用
扫描仪
类
String result = "";
Scanner in = new Scanner(new FileInputStream(file));
while(in.hasNextLine())
result += in.nextLine() + ",";
这将创建如下字符串:
text1、text2、longtext3等。
您可以使用InputStreamReader()
将它放在InputStream和BufferedReader之间。现在您不需要文件实例(因此不需要先保存它)
类似于
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(","));
}
...
InputStream input=new BufferedInputStream(connection.getInputStream());
BufferedReader reader=新的BufferedReader(新的InputStreamReader(输入));
弦线;
而((line=br.readLine())!=null){
列表。添加(行);
//进一步将该行拆分为逗号分隔的值列表
List commaSeparatedValues=Arrays.asList(第.split行(“,”);
}
...
我不确定你在问什么,但我认为你想保存文本文件的每一行。这对我来说很有效,它把每一行都放在一根长线上
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”…不要使用字符串连接。你只剩下几十个。成百上千个字符串实例(取决于文件大小),等待gc删除它们。浪费记忆和时间。最好使用StringBuilder#append代替()