Does anyone know why this crashes? All I'm doing is reading in a file in a txt file from my raw folder and when I click the load button in the other activity window, the code breaks when I call the variable testing within the file reader object upon click. log.d(null, ReadFileObject.fileText) Thanks in advance!
public class ReadFile extends Activity{
public String test;
public String testing;
protected void onCreate(Bundle savedInstanceState) {
}
public void fileText() {
InputStream fis;
fis = getResources().openRawResource(R.raw.checkit);
byte[] input;
try {
input = new byte [fis.available()];
while(fis.read() != -1)
{
test += new String (input);
}
testing = test;
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}
/* InputStream fis = null;
try {
fis = getResources().openRawResource(R.raw.checkit);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String nextLine;
int i = 0, j = 0;
while ((nextLine = br.readLine()) != null) {
if (j == 5) {
j = 0;
i++;
}
test += nextLine;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
} finally {
if (fis != null) {
try { fis.close(); }
catch (IOException ignored) {}
}
}*/
}
}
Your code is broken here:
byte[] input;
input = new byte [fis.available()];
while(fis.read() != -1) {
test += new String (input);
}
testing = test;
fis.close();
In Java available() is unreliable (read the Javadoc).... and may even return 0. You should instead use a loop similar to:
InputStream fis = getResources().openRawResource(R.raw.checkit);
try {
byte[] buffer = new byte[4096]; // 4K buffer
int len = 0;
while((len = fis.read(buffer)) != -1) {
test += new String (buffer, 0, len);
}
testing = test;
} catch (IOException ioe) {
ioe.printStackTrace();
// make sure you do any other appropriate handling.
} finally {
fis.close();
}
(although using string concatenation is probably not the best idea, use a StringBuilder).
Your class extends `activity but theres nothing inside oncreate. If you need a simple java program try to create New java Project . Since you extend activity you should setcontentview(yourLayout). Then call your method from oncreate and do your stuffs
Related
I wrote an example of FileInputStream,But I found that if I use read() directly in the loop, there will be a problem with the printed data, and it cannot be displayed completely. After using the int variable to receive the return value of read(), it can be displayed normally here. Why?
code:
String path = "d:/hello.txt";
FileInputStream fileInputStream = null;
int readData = 0;
try {
fileInputStream = new FileInputStream(path);
while ((readData = fileInputStream.read()) != -1) {
System.out.print((char) readData);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I am a beginner in android. I am trying to work on Sockets. But my InputStream is not reading the data as expected. It is getting out of the method after j = inputStream.read(arrayOfByte, 0, i); Please help me.
public void readinputstreamforid(final String ip, final int port){
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
try {
socket=new Socket(ip,port);
} catch (IOException e) {
e.printStackTrace();
}
final byte[] arrayOfByte = new byte[10000];
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
while (socket.isConnected()) {
int j = 0;
int i = arrayOfByte.length;
try {
j = inputStream.read(arrayOfByte, 0, i);
if (j == -1)
throw new IOException("not working");
if (j == 0)
continue;
} catch (IOException e) {
e.printStackTrace();
}
final String strData = new String(arrayOfByte, 0, j).replace("\r", "").replace("\n", "");
Log.d("hello","recieved: "+strData);
}
try {
IOUtils.write("!##\n",socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
asyncTask.execute();
}
If an error happens, you are logging it, but then you continue with the code, where more errors can then happen. When an error happens, STOP looping and exit the function. InputStream.read() returns -1 when the end of the stream is reached. For a socket, that means when the connection is closed. That is not really an error condition, so you don't need to throw an exception. Just break the loop. You can wrap the InputStream inside of a BufferedReader so you can use its readLine() method instead of reading bytes manually.
Also, you are trying to write to the socket's OutputStream after the socket has already disconnected. That will never work.
Try something more like this:
public void readinputstreamforid(final String ip, final int port){
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
try {
socket = new Socket(ip, port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
OutputDataStream out = socket.getOutputStream();
do {
String data = in.readLine();
if (data == null)
break;
Log.d("hello", data);
IOUtils.write("!##\n", out, StandardCharsets.UTF_8);
}
while (true);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
asyncTask.execute();
}
I am using a FileOutputStream to create a file in an activity that is not my MainActivity. The file is created, and when I destroy the activity, the data I want is written, but when I relaunch the activity from my MainActivity, the file cannot be found. What can I change in my code so that I don't get a fileNotFoundException? The relevant code is here:
try {
fis = new FileInputStream("words");
ois = new ObjectInputStream(fis);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
EOFException eof = null;
int counter = 0;
if (fnfexception == null) {
while (eof == null) {
try {
if (words == null) words = new Dict[1];
else words = Arrays.copyOf(words, counter + 1);
words[counter] = (Dict) ois.readObject();
counter++;
} catch (EOFException end) {
eof = end;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
wordStartCount = counter;
wordCount = counter;
fnfexception = null;
try {
fos = openFileOutput("words", Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
You used wrong way to read from an internal file, use the following code
try {
FileInputStream fis = context.openFileInput("file_name");
int content;
StringBuilder str = new StringBuilder();
while ((content = fis.read()) != -1)
str.append((char) content);
fis.close();
String savedText = str.toString();
} catch (IOException e) {
e.printStackTrace();
}
How can I add a executable into assets and run it in Android and show the output?
I've a executable that will work. I assume there will need to be some chmod in the code.
Thank you.
here is my answer
put copyAssets() to your mainactivity.
someone's code:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getFilesDir(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
also here is code to run command
public String runcmd(String cmd){
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer out = new StringBuffer();
while ((read = in.read(buffer)) > 0) {
out.append(buffer, 0, read);
}
in.close();
p.waitFor();
return out.substring(0);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
you may need to change it to
String prog= "programname";
String[] env= { "parameter 1","p2"};
File dir= new File(getFilesDir().getAbsolutePath());
Process p = Runtime.getRuntime().exec(prog,env,dir);
to ensure proper parameter handling
also add this to your main code
to check proper copying of files
String s;
File file4 = new File(getFilesDir().getAbsolutePath()+"/executable");
file4.setExecutable(true);
s+=file4.getName();
s+=file4.exists();
s+=file4.canExecute();
s+=file4.length();
//output s however you want it
should write: filename, true, true, correct filelength.
Place your executable in raw folder, then run it by using ProcessBuilder or Runtime.exec like they do here http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App
Have a file on specified path /foo/file-a.txt and that file contains a path of another file
file-a.txt contains: /bar/file-b.txt this path at line one. need to parse the path of file-b.txt and zip that file and move that zipped file to another path /too/ from my Java code.
I been till the below code then i m stuck.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Reader
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
String CurrentLine;
br = new BufferedReader(new FileReader("/foo/file-a.txt"));
while ((CurrentLine = br.readLine()) != null)
{
System.out.println(CurrentLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
am getting path as text, help would be appreciated. Thanks in advance
For the actual zipping of the file, this page may be of help.
As a general note, this code will replace the current existing zip file.
public class TestZip02 {
public static void main(String[] args) {
try {
zip(new File("TextFiles.zip"), new File("sample.txt"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void zip(File zip, File file) throws IOException {
ZipOutputStream zos = null;
try {
String name = file.getName();
zos = new ZipOutputStream(new FileOutputStream(zip));
ZipEntry entry = new ZipEntry(name);
zos.putNextEntry(entry);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fis.read(byteBuffer)) != -1) {
zos.write(byteBuffer, 0, bytesRead);
}
zos.flush();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
zos.closeEntry();
zos.flush();
} finally {
try {
zos.close();
} catch (Exception e) {
}
}
}
}
For moving the file, you can use File.renameTo, here's an example.
Hope this helps!