how to save contents of a file as single string using java - java

I am trying to extract a specific content from text file by using delimiters. This is my code :
File file = new File("C:\\Inputfiles\\message.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
System.out.println(strings);}
But as a result, each and everyline is getting splitted by delimiter and saved as array.
Can anyone suggest how I can save the contents from file as a single string, so I can get limited number of lines only as Array.

You can use StringBuilder or StringBuffer to do that.
File file = new File("C:\\Inputfiles\\message.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
StringBuilder singleString = new StringBuilder();
for(String s : strings){
singleString.append(s);
}
System.out.println(singleString.toString());
}

Thanks All,
I did using below changes
String contents = new String(Files.readAllBytes(Paths.get("C:\\Inputfiles\\message1.txt")));
String[] splitted = StringUtils.split(contents, "-------");
for(int i=0;i<splitted.length;i++)
System.out.println(splitted[i]);

Related

Java - Only read first line of a file

I only want to read the first line of a text file and put that first line in a string array.
This is what I have but its reading the whole file.
ex text in myTextFile:
Header1,Header2,Header3,Header4,Header5
1,2,3,4,5
6,7,8,9,10
String line= System.getProperty("line.separator");
String strArray[] = new String[5];
String text = null;
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
text = brTest .readLine();
while (text != line) {
System.out.println("text = " + text );
strArray= text.split(",");
}
use BufferedReader.readLine() to get the first line.
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
text = brTest .readLine();
System.out.println("Firstline is : " + text);
If I understand you, then
String text = brTest.readLine();
// Stop. text is the first line.
System.out.println(text);
String[] strArray = text.split(",");
System.out.println(Arrays.toString(strArray));
With Java 8 and java.nio you can also do the following:
String myTextFile = "path/to/your/file.txt";
Path myPath = Paths.get(myTextFile);
String[] strArray = Files.lines(myPath)
.map(s -> s.split(","))
.findFirst()
.get();
If TAsks assumption is correct, you can realize that with an additional
.filter(s -> !s.equals(""))
Also, beside of all other solutions presented here, you could use guava utility class (Files), like below:
import com.google.common.io.Files;
//...
String firstLine = Files.asCharSource(myTextFile).readFirstLine();
I think you are trying to get one line only if it's not empty.
You can use
while ((text=brTest .readLine())!=null){
if(!text.equals("")){//Ommit Empty lines
System.out.println("text = " + text );
strArray= text.split(",");
System.out.println(Arrays.toString(strArray));
break;
}
}
Use this
BuffereedReader reader = new BufferedReader(new FileReader(textFile));
StringBuilder builder = new StringBuilder();
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
break;
}
if(sb.toString.trim().length!=0)
System.out.println("first line"+sb.toString);
I hope this will help someone
to read the first line:
public static String getFirstLine() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = br.readLine();
br.close();
return line;
}
to read the whole text:
public static String getText() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line).append("\n");
line = br.readLine();
}
String fileAsString = sb.toString();
br.close();
return fileAsString;
}
You need to change the condition of your loop
String[] nextLine;
while((nextLine = brTest.readLine()) != null) {
...
}
ReadLine reads each line from beginning up to the occurrence of \r andor \n
You can also use tokenizer to split the string
String[] test = "this is a test".split("\\s");
In addition it seems the file is of type CSV if it is please mention that in the question.

How to convert xml file to string without escaping XML using java

I've a XML file and want to send its content to caller as string. This is what I'm using:
return FileUtils.readFileToString(xmlFile);
but this (or that matter all other ways I tried like reading line by line) escapes XML elements and enclose whole XML with <string> like this
<string>>&lt;.....</string>
but I want to return
<a>....</a>
I'd advise using a different file reader maybe something like this.
private String readFile( String file ) throws IOException {
BufferedReader reader = new BufferedReader( new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
return stringBuilder.toString();
}
It's probably a feature of file utils.
According to your question you just want to read the file. You can use FileReader and BufferedReader to read the file.
File f=new File("demo.xml");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
String line;
while((line=br.readLine())!=null)
{
System.out.println(line);
}
Hope this answer helps you
IOUtils works well. It's in package org.apache.commons.io. The toString method takes an InputStream as a parameter and returns the contents as a string maintaining format.
InputStream is = getClass.getResourceAsStream("foo.xml");
String str = IOUtils.toString(is);
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
String line;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!= null){
sb.append(line.trim());
}

Text processing in java android

I have a file that looks similar to this
12345 one
12345 two
12345 three
.......
Question is how can i get all of the values from second row and store them in a String[]
i know how to read file in java just dont know how to cut the second row
1. Store Each line from the file into an ArrayList<String>, its more flexible than String[] array.
2. Then access the line you need by get() method of ArrayList
Eg:
ArraList<String> arr = new ArrayList<String>();
//Now add each lines into this arr ArrayList
arr.get(1); // Getting the Second Line from the file
`
You can split the file line by new line.
String [] names = fileString.split("\n");
Ok this is what i did but it skips first line
FileInputStream fstream = new FileInputStream("/sys..........");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
strLine = br.readLine();
while ((strLine = br.readLine()) != null) {
delims = strLine.split(" ");
first = delims[1];
where.add(first);
}
in.close();
From example above it contains only "two" and "three"

Java - Parsing Text File

I have an input text file in this format:
<target1> : <dep1> <dep2> ...
<target2> : <dep1> <dep2> ...
...
And a method that takes two parameters
function(target, dep);
I need to get this parsing to call my method with each target and dep eg:
function(target1, dep1);
function(target1, dep2);
function(target1, ...);
function(target2, dep1);
function(target2, dep2);
function(target2, ...);
What would be the most efficient way to call function(target,dep) on each line of a text file? I tried fooling around with the scanner and string.split but was unsuccessful. I'm stumped.
Thanks.
Read line into String myLine
split myLine on : into String[] array1
split array1[1] on ' ' into String[] array2
Iterate through array2 and call function(array1[0], array2[i])
So ...
FileReader input = new FileReader("myFile");
BufferedReader bufRead = new BufferedReader(input);
String myLine = null;
while ( (myLine = bufRead.readLine()) != null)
{
String[] array1 = myLine.split(":");
// check to make sure you have valid data
String[] array2 = array1[1].split(" ");
for (int i = 0; i < array2.length; i++)
function(array1[0], array2[i]);
}
The firstly you have to read line from file and after this split read line, so your code should be like:
FileInputStream fstream = new FileInputStream("your file name");
// or using Scaner
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// split string and call your function
}

How to read a String (file) to array in java

Suppose there is a file named as SUN.txt
File contains : a,b,dd,ss,
I want to make dynamic array depending upon the number of attributes in file.
If ther is a char after comma then array will be of 0-4 i.e of length 5.
In the above mentioned case there is no Char which returns 0-3 Array of length 4. I want to read the NULL after comma too.
How do i do that?
Sundhas
You should think about
Reading the file into a String
Splitting the file by separator ','
Using a list for adding the characters and convert the list to an array, when the list is filled
As Markus said, you want to do something like this..
//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//The StringBuffer will be used to create a string if your file has multiple lines
StringBuffer sb = new StringBuffer();
String line;
while((line = reader.readLine())!= null)
{
sb.append(line);
}
//We now split the line on the "," to get a string array of the values
String [] store = sb.toString().split(",");
I do not quite understand why you would want the NULL after the comma? I am assuming that you mean after the last comma you would like that to be null in your array? I do not quite see the point in that but that is not what the question is.
If that is the case you wont read in a NULL, if after the comma there was a space, you could read that in.
If you would like a NULL you would have to add it in yourself at the end so you could do something like
//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//Use an arraylist to store the values including nulls
ArrayList<String> store = new ArrayList<String>();
String line;
while((line = reader.readLine())!= null)
{
String [] splitLine = line.split(",");
for(String x : splitLine)
{
store.add(line);
}
//This tests to see if the last character of the line is , and will add a null into the array list
if(line.endsWith(","))
store.add(null);
}
String [] storeWithNull = store.toArray();
Well if you want want to simply open the file and store the content in a array of string then
1) open the file into a string
2) split the string using a regex "," http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)
but I'm curious why you can't use a String file directly ?
For your datatructure, use a list of arrays. Each list entry is a line of your textfile, each entry is an array that holds the comma separated values:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
data.add(line.split(","));
line = readNextLine();
}
(assuming, your file contains 1..n lines of comma separated values)
You may want to have it like this:
"a,b,c,d," -> {"a", "b", "c", "d", null}
Here's a suggestion how to solve that problem:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
String[] values = new String[5];
String[] pieces = line.split(",");
for (int i = 0; i<pieces.length; i++)
values[i] = pieces[i];
data.add(values);
line = readNextLine();
}
its seems like a CSV file something like this will work assuming it has 5 lines and 5 values
String [][] value = new String [5][5];
File file = new File("SUN.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
int row = 0;
int col = 0;
while((line = br.readLine()) != null ){
StringTokenizer s = new StringTokenizer(line,",");
while (s.hasMoreTokens()){
value[row][col] = s.nextToken();
col++;
}
col = 0;
row++;
}
i havent tested this code
Read the file, using BufferedReader, one line at the time.
Use split(",", -1) to convert to an array of String[] including also empty strings beyond the last comma as part of your array.
Load the String[] parts into a List.

Categories