How to get intput stream from .txt file ( android )? - java

I want to read my data from my .txt file into a ReaderClass in android, fields are seperated by ";"
---- here is my solution of my last post:
public void cut()
{
try{
InputStream input =context.getResources().openRawResource(R.raw.textfile);
BufferedReader br = null;
br=new BufferedReader(new InputStreamReader(input,"iso-8859-1"));
String line = null;
while ((line = br.readLine()) != null) {
String[] decoupage= line.split(";");
String titre=decoupage[0];
String description=decoupage[1];
String reponse=decoupage[2];
String explication=decoupage[3];
String categorie=decoupage[4];
String etat=decoupage[5];
//test Logcat
Log.d("information ", " buffer");
Log.i("titre : ",titre);
Log.i("description : ",description);
Log.i("reponse : ",reponse);
Log.i("explication : ",explication);
Log.i("categorie : ",categorie);
Log.i("etat : ",etat);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
System.err.println("\n File not found");
}
//end
}

FileInputStream fis;
fis = openFileInput("sample.txt");
StringBuffer Content = new StringBuffer("");
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
Content.append(new String(buffer));
}
you will get entire content in a string buffer ,convert it into string, then you can apply yourString.split(";") to get all values which you can keep in some array.

Related

Read complete file without looping in android

i need a solution for reading a text file which was stored in internal storage.
i don't want to read it line by line. without use looping how to read a complete text file and store it into a string.
BufferedReader br;
String line;
String data = "";
// String text="";
try {
br = new BufferedReader(new FileReader(new File(Environment.getExternalStorageDirectory(), "queue_mgr.txt")));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
}
You can use a large byte buffer and gain some efficiency:
try
{
InputStream in = new FileInputStream (from);
OutputStream out = new FileOutputStream (to);
// Transfer bytes from in to out
byte[] buf = new byte[1024 * 10]; // 5MB would be about 500 iterations
int len;
while ((len = in.read (buf)) > 0)
out.write (buf, 0, len);
in.close ();
out.close ();
}
}
catch (FileNotFoundException e)
{
...
}
catch (IOException e)
{
...
}

Android download txt from website without removing wrap

I need to download a .txt file from a website, the problem is the downloaded file doesn't respect the same line wrapping as the original file.
File:
Word1
Word2
Word3
File downloaded:
Word1Word2Word3
I use this method to download (this isn't mine) :
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream( MegaMethods.FolderPath+"downloadedfile.txt");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
Try using a BufferedReader to read it in something like
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuilder responseData = new StringBuilder();
while((line = in.readLine()) != null) {
responseData.append(line);
}
then output the lines as necessary. I'm no where near a station where I can test this so you might have to do some fiddling.

Save content of File as String in Java?

I was working a little bit with config files and file reader classes in java.
I always read/wrote in the files with arrays because I was working with objects.
This looked a little bit like this:
public void loadUserData(ArrayList<User> arraylist) {
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for(String line : lines) {
String[] userParams = line.split(";");
String name = userParams[0];
String number= userParams[1];
String mail = userParams[2];
arraylist.add(new User(name, number, mail));
}
} catch (IOException e) {
e.printStackTrace();
}
}
This works fine, but how can I save the content of a file as only one single string?
When I read a file, the string I use should be the exact same as the content of the file (without the use of arrays or line splits).
how can I do that?
Edit:
I try to read a SQL-Statement out of a file to use it with JDBC later on. That's why I need the content of the File as a single String
This method will work
public static void readFromFile() throws Exception{
FileReader fIn = new FileReader("D:\\Test.txt");
BufferedReader br = new BufferedReader(fIn);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
String text = sb.toString();
System.out.println(text);
}
I hope this is what you need:
public void loadUserData(ArrayList<User> arraylist) {
StringBuilder sb = new StringBuilder();
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for(String line : lines) {
// String[] userParams = line.split(";");
//String name = userParams[0];
//String number= userParams[1];
//String mail = userParams[2];
sb.append(line);
}
String jdbcString = sb.toString();
System.out.println("JDBC statements read from file: " + jdbcString );
} catch (IOException e) {
e.printStackTrace();
}
}
or maybe this:
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);
Just do that:
final FileChannel fc;
final String theFullStuff;
try (
fc = FileChannel.open(path, StandardOpenOptions.READ);
) {
final ByteBuffer buf = ByteBuffer.allocate(fc.size());
fc.read(buf);
theFullStuff = new String(buf.array(), theCharset);
}
nio for the win! :p
You could always create a Buffered reader e.g.
File anInputFile = new File(/*input path*/);
FileReader aFileReader = new FileReader(anInputFile);
BufferedReader reader = new BufferedReader(aFileReader)
String yourSingleString = "";
String aLine = reader.readLine();
while(aLine != null)
{
singleString += aLine + " ";
aLine = reader.readLine();
}

very long string as a response of web service

I am getting a really long string as the response of the web service I am collecting it in the using the StringBuilder but I am unable to obtain the full value I also used StringBuffer but had no success.
Here is the code I am using:
private static String read(InputStream in ) throws IOException {
//StringBuilder sb = new StringBuilder(1000);
StringBuffer sb = new StringBuffer();
String s = "";
BufferedReader r = new BufferedReader(new InputStreamReader( in ), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
s += line;
} in .close();
System.out.println("Response from Input Stream Reader >>>" + sb.toString());
System.out.println("Response from Input S >>>>>>>>>>>>" + s);
return sb.toString();
}
Any help is appreciated.
You can also split the string in array of strings in order to see all of them
String delimiter = "put a delimiter here e.g.: \n";
String[] datas=sb.toString().split(delimiter);
for(String string datas){
System.out.println("Response from Input S >>>>>>>>>>>>" + string);
}
The String may not print entirely to the console, but it is actually there. Save it to a file in order to see it.
I do not think that your input is too big for a String, but only not shown to the console because it doesn't accept too long lines. Anyways, here is the solution for a really huge input as characters:
private static String[] readHugeStream(InputStream in) throws IOException {
LinkedList<String> dataList = new LinkedList<>();
boolean finished = false;
//
BufferedReader r = new BufferedReader(new InputStreamReader(in), 0xFFFFFF);
String line = r.readLine();
while (!finished) {
int lengthRead = 0;
StringBuilder sb = new StringBuilder();
while (!finished) {
line = r.readLine();
if (line == null) {
finished = true;
} else {
lengthRead += line.length();
if (lengthRead == Integer.MAX_VALUE) {
break;
}
sb.append(line);
}
}
if (sb.length() != 0) {
dataList.add(sb.toString());
}
}
in.close();
String[] data = dataList.toArray(new String[]{});
///
return data;
}
public static void main(String[] args) {
try {
String[] data = readHugeStream(new FileInputStream("<big file>"));
} catch (IOException ex) {
Logger.getLogger(StackoverflowStringLong.class.getName()).log(Level.SEVERE, null, ex);
} catch (OutOfMemoryError ex) {
System.out.println("out of memory...");
}
}
System.out.println() does not print all the characters , it can display only limited number of characters in console. You can create a file in SD card and copy the string there as a text document to check your exact response.
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Responsefromserver");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, "response.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(totalResponse);
writer.flush();
writer.close();
}
catch(IOException e)
{
System.out.println("Error:::::::::::::"+e.getMessage());
throw e;
}

Process binary file in Java using FileItemStream

I have a webapplication which allows to upload binary files. I have to parse them and save the content 1:1 into a String and then into the database.
When I use uuencode on a unix machine to encode the binary file, then it works. Is there a way to do this automatically in java?
if (isMultipart) {
//Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
//Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (!item.isFormField()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
licenseString = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
// Generate License File
licenseString += line + "\n";
}
}
}
session.setAttribute("licenseFile", licenseString);
System.out.println("adding licensestring to session. ");
}
It works of course for all non-binary files uploaded. How can I extend it to support binary files?
// save to file
// =======================================
InputStream is = new BufferedInputStream(item.openStream());
BufferedOutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream("temp.txt", false));
int data = -1;
while ((data = is.read()) != -1) {
output.write(data);
}
} finally {
is.close();
output.close();
}
// read content of file
// =======================================
System.out.println("content of file:");
try {
FileInputStream fstream = new FileInputStream("temp.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
licenseString = "";
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(javax.xml.bind.DatatypeConverter.printBase64Binary(strLine.getBytes()));
licenseString += javax.xml.bind.DatatypeConverter.printBase64Binary(strLine.getBytes()) + "\n";
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
You could use the commons_fileupload lib (check it here : org.apache.commons.fileupload.disk.DiskFileItem is not created properly?)
The doc is here : http://commons.apache.org/fileupload/using.html
Your case is pretty well explained on the official website.
A Better way would be to write the upload to a temporary file and then handle it from there:
if (!item.isFormField()) {
InputStream stream = new BufferedInputStream(item.getInputStream());
BufferedOutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(your_temp_file, false));
int data = -1;
while ((data = input.read()) != -1) {
output.write(data);
}
} finally {
input.close();
output.close();
}
}
now you have a temporary file, which is the same as the uploaded file, you can do your 'other' calculations from there.

Categories