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>><.....</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());
}
Related
Hi I'm currently having issues with reading in a file in android studio. The file I want to read in is just a simple text file called test. This is the path of the file C:\Users\John\Documents\MadLibs\app\src\main\res\raw\test.txt. Here's what I'm trying:
BufferedReader br = new BufferedReader(new FileReader(getResources().openRawResourceFd(R.raw.test)));
I'm relitively new to android studio and really don't understand how to read in files. I assumed its just like java however everything I've tried fails. Anyone have any ideas?
Reading a textfile in android studio
FileInputStream fileInputStream=openFileInput("file.txt");
InputStreamReader InputRead= new InputStreamReader(fileInputStream);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
String rs=String.copyValueOf(inputBuffer,0,charRead);
s +=rs;
}
InputRead.close();
Log.d(TAG,s);
To read a text file as a string, you can use the following method:
// #RawRes will gives you warning if rawId is not from correct id for raw file.
private String readRawFile(#RawRes int rawId) {
String line;
try {
InputStream is = getResources().openRawResource(rawId);
// read the file as UTF-8 text.
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// Or using the following if API >= 19
//BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
inputStream.close();
line = result.toString();
} catch (IOException e) {
line = null;
}
return line;
}
I am trying to read a file using BufferedReader, but when I tried to print, It is returning some weird characters.
Code of reading file is:
private static String readJsonFile(String fileName) throws IOException{
BufferedReader br = null;
try {
StringBuilder sb = new StringBuilder();
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while(line != null ){
sb.append(line);
System.out.println(line);
line=br.readLine();
}
return sb.toString();
} finally{
br.close();
}
}
This function is being called as :
String jsonString = null;
try {
jsonString = readJsonFile(fileName);
} catch (IOException e) {
e.printStackTrace();
}
But when I tried to print this in console using System.out.println(jsonString);, It is returning some fancy pictures.
Note: It is Working file when file size is small.
Is there any limit on size of file it can read ?
You're using the platform default encoding to read the file, which is probably encoded in UTF8. Check the actual encoding of the file, and specify the encoding:
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream("...", StandardCharsets.UTF_8));
Note that since you simply want to read everything from the file, you could simply use
String json = new String(Files.readAllBytes(...), StandardCharsets.UTF_8);
i got the list of applications from cmd command using /output:D:\list.txt product get name,version. However when i try to retrieve the list using java the output has white spaces after each letter.
SAMPLE:
from text file
links
images
lists
when read in java
l i n k s
i m a g e s
l i s t s
is there a way to fix this problem?
i just used this code:
public void myreader() throws IOException {
Path path = Paths.get("D:\\list.txt");
Charset charset = Charset.forName("ISO-8859-1");
try (BufferedReader reader = Files.newBufferedReader(path,charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
This can be due to the encoding problem. Try using UTF-16 character set
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-16"));
Have you tried the FileReader?
FileReader fileReader;
try {
fileReader = new FileReader( "D:\\list.txt" );
BufferedReader bufferedReader = new BufferedReader( fileReader );
String line;
while( ( line = bufferedReader.readLine() ) != null )
{
System.out.println( line );
}
fileReader.close();
} catch ( IOException except ) {
System.err.println( except.getStackTrace()[0] );
}
Im not shure where your problem is coming from, but you may take the FileReader for such instructions.
Looks like you read a UTF-16 encoded file.
Give a hint to your Reader - pass "UTF-16", instead of "ISO-8859-1".
I have a file of words in text.I want to read the file
FileInputStream fstream = new FileInputStream(s);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
MaxentTagger tagger = new MaxentTagger("tag/wsj-0-18-bidirectional-distsim.tagger");
String tagged = tagger.tagString(br);
My problem is it should read the file and give line by line of the file as string to the tagger and print in a output file.
As both input and output are going to be text, I'd use Reader and Writer rather than streams. Something like:
try (
BufferedReader in = new BufferedReader(new FileReader("inputFile.txt"));
PrintWriter out = new PrinterWriter(new FileWriter("outputFile.txt"));
) {
MaxentTagger tagger = new MaxentTagger("tag/wsj-0-18-bidirectional-distsim.tagger");
String line;
while ((line = in.readLine()) != null) {
String tagged = tagger.tagString(line);
out.println(tagged);
}
}
Note, this code uses Java 7 resource handling, so the in and out are closed automatically.
Suppose a file contains the following lines:
#Do
#not
#use
#these
#lines.
Use
these.
My aim is to read only those lines which does not start with #. How this can be optimally done in Java?
Let's assume that you want to accumulate the lines (of course you can do everything with each line).
String filePath = "somePath\\lines.txt";
// Lines accumulator.
ArrayList<String> filteredLines = new ArrayList<String>();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = bufferedReader.readLine()) != null) {
// Line filtering. Please note that empty lines
// will match this criteria!
if (!line.startsWith("#")) {
filteredLines.add(line);
}
}
}
finally {
if (bufferedReader != null)
bufferedReader.close();
}
Using Java 7 try-with-resources statement:
String filePath = "somePath\\lines.txt";
ArrayList<String> filteredLines = new ArrayList<String>();
try (Reader reader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(reader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
if (!line.startsWith("#"))
filteredLines.add(line);
}
}
Use the String.startsWith() method. in your case you would use
if(!myString.startsWith("#"))
{
//some code here
}
BufferedReader.readLine() return a String. you could check if that line starts with # using string.startsWith()
FileReader reader = new FileReader("file1.txt");
BufferedReader br = new BufferedReader(reader);
String line="";
while((line=br.readLine())!=null){
if(!line.startsWith("#")){
System.out.println(line);
}
}
}