Bufferedreader returning null - java

i'm trying to read a web address from a text and then have the app open that address, my buffered reader seems to be reading the lines correctly but readline keeps coming back null
String rsslink = null;
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rsslink = br.readLine()) != null)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink;
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));

You will get the last line that is null rsslink.
You need to change your loop
try {
while ((rsslink = br.readLine()) != null)
{
}
}
to
try {
StringBuilder sb= new StringBuilder();
while ((rsslink = br.readLine()) != null)
{
sb.append(rsslink);
}
rsslink = sb.toString();
}

Use this:
String rsslink = "";
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink +=line ;
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink;
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
Better your StringBuffer orStringBuilder.
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink.toString();

Related

Get range of lines in file

i would like to save in a string multiple lines from reading file, eg: I am reading one file.txt with the following content:
def var x as int.
def var y as char.
procedure something:
//here some content
end.
I would like to catch content between "procedure" and "end".
public static void main(String[] args) {
String piContent = "";
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(line.contains("procedure")){
piContent = line;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I appreciate any help.
final StringBuilder sb = new StringBuilder();
try (final BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
String line;
boolean rememberStuff = false;
while ((line = br.readLine()) != null) {
if (line.startsWith("procedure ")) {
rememberStuff = true;
} else if (line.startsWith("end.")) {
rememberStuff = false;
} else if (rememberStuff) {
sb.append(line).append('\n');
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.err.println("Lines found between procedure and end:");
System.err.println(sb);
public static String getContentFromFile(Path file) throws IOException {
StringBuilder buf = new StringBuilder();
boolean add = false;
for (String line : Files.readAllLines(file)) {
if ("end.".equalsIgnoreCase(line.trim()))
break;
if (add)
buf.append(line).append(System.lineSeparator());
else if ("procedure something:".equalsIgnoreCase(line.trim()))
add = true;
}
return buf.toString();
}

Improper_Restriction_of_XXE_REF

I'm new to using the Checkmarx tool and just checking for security flaws in code in general. I have a method which is supposed to read from an input stream. The method works, however I am getting XXE and SSRF errors.
public static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(Normalizer.normalize(line, Normalizer.Form.NFD));
}
} catch (IOException e) {
LOG.error(
"********************",
e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
LOG.error(
******************,
e);
}
}
}
return sb.toString();
}

Saving to Android Internal Storage

At the moment i'm trying to save a response to the internal storage in the phone. Everything works fine up until i try and retrieve the data again. When i log out the retrieved data it only logs out one small section of the response and the rest isn't there. Ive tried deleting the file and calling it again just incase it was using an old one.
Saving Code
try {
String response = apiResponse.getRawResponse();
Log.e("Response", response);
FileOutputStream userInfo = openFileOutput("personal_profile", MODE_PRIVATE);
userInfo.write(response.getBytes());
userInfo.close();
} catch (Exception e) {
e.printStackTrace();
Retrieving Code
String response = "";
try {
FileInputStream fis = getActivity().openFileInput("personal_profile");
DataInputStream isr = new DataInputStream(fis);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
line = response;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("Saved File", response);
Any kind of suggestions would be great!
REASON
The problem was that the line variable is assigned again in every iteration
Try this:
String response = "";
try {
FileInputStream fis = getActivity().openFileInput("personal_profile");
DataInputStream isr = new DataInputStream(fis);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
line = response;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
CHANGE LAST LINE
Log.e("Saved File", sb.toString());
Have you got this in your AndroidManifest.xml file?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also, this link has everything you need to know about reading and writing files:
http://www.anddev.org/working_with_files-t115.html
Code::
String response = "";
try {
FileInputStream fis = getActivity().openFileInput("personal_profile");
DataInputStream isr = new DataInputStream(fis);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
line = response;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("Saved File", sb.toString());

Java readLine from Com port

is any way to change this java code (read from com port) to read lines ?
eg.
I'm using rxtx com
original method:
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[10];
int numBytes = 0;
try {
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
}
} catch (IOException e) {
System.out.println(e);
}
System.out.println(Arrays.toString(readBuffer));
}
}
Assuming inputStream is an InputStream, you could wrap it with an InputStreamReader and wrap that with a BufferedReader (that has a readLine()). Something like,
case SerialPortEvent.DATA_AVAILABLE:
String line;
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
or you could possible use with try-with-resouces,
case SerialPortEvent.DATA_AVAILABLE:
String line;
BufferedReader br = null;
try (br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}

How to open a txt file located on the web and read its contents to a string?

I have looked around on how to do this and I keep finding different solutions, none of which has worked fine for me and I don't understand why. Does FileReader only work for local files? I tried a combination of scripts found on the site and it still doesn't quite work, it just throws an exception and leaves me with ERROR for the variable content. Here's the code I've been using unsuccessfully:
public String downloadfile(String link){
String content = "";
try {
URL url = new URL(link);
URLConnection conexion = url.openConnection();
conexion.connect();
InputStream is = url.openStream();
BufferedReader br = new BufferedReader( new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
content = sb.toString();
br.close();
is.close();
} catch (Exception e) {
content = "ERROR";
Log.e("ERROR DOWNLOADING",
"File not Found" + e.getMessage());
}
return content;
}
Use this as a downloader(provide a path to save your file(along with the extension) and the exact link of the text file)
public static void downloader(String fileName, String url) throws IOException {
File file = new File(fileName);
url = url.replace(" ", "%20");
URL website = new URL(url);
if (file.exists()) {
file.delete();
}
if (!file.exists()) {
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
}
}
Then call this function to read the text file
public static String[] read(String fileName) {
String result[] = null;
Vector v = new Vector(10, 2);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String tmp = "";
while ((tmp = br.readLine()) != null) {
v.add(tmp);
}
Iterator i = v.iterator();
result = new String[v.toArray().length];
int count = 0;
while (i.hasNext()) {
result[count++] = i.next().toString();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return (result);
}
And then finally the main method
public static void main(){
downloader("D:\\file.txt","http://www.abcd.com/textFile.txt");
String data[]=read("D:\\file.txt");
}
try this:
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder();
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
sb.append(str );
}
in.close();
String serverTextAsString = sb.toString();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

Categories

Resources