I'm saving a file to a non-default spot in Android and am trying to be able to open it to load information from it but cannot find a way to specify the path to the file...
Here is how I am saving the file...
File directory = new File(path + "/Android/data/com.etechtour/save_data/");
directory.mkdirs();
extStorageDirectory = path.toString() + "/Android/data/com.etechtour/save_data/";
File file = new File(extStorageDirectory, "pumpItUpGas.txt");
try
{
outStream = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(outStream);
out.write("Record#: " + record + ", Nickname: " + nickname + ", Year: " + year + ", Make: " + make + ", Model: " + model);
out.flush();
out.close();
outStream.flush();
outStream.close();
}
Now I've successfully saved the file to this location, but when trying to access it I can't figure out ANYTHING that works to set the path to load the file. I've looked around everywhere online and can't seem to find anything that works except using the default save position. Here's how I'm trying to load but am either forceclosing or getting null pointer exceptions
try
{
String filename = Environment.getExternalStorageDirectory().toString() + "/Android/data/com.etechtour/save_data/pumpItUpGas.txt";
InputStream in = openFileInput("pumpItUpGas.txt");
//FileReader fileReader = new FileReader(file);
//FileInputStream fileInput = new FileInputStream(path);
if (in != null)
//if (fileReader != null)
{
InputStreamReader temp = new InputStreamReader(in);
//InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(temp);
StringBuffer buf = new StringBuffer();
while ((str = reader.readLine()) != null)
{
buf.append(str);
}
//fileInput.close();
in.close();
return str;
}
}
Any help would be greatly appreciated. Thanks
Use FileInputStream or FileReader with your File object, just like normal Java I/O.
Related
I am using the sample from Microsoft's Async Socket Listener. I got everything working fine, I am able to send files and data etc. However, I am struggling with trying to keep the socket open. I do not want to close the socket and re-open for every file I am sending. I want to keep it open until all files are sent. I assume the issue is in the 'SendCallback' but I can not seem to get it to work.
.Net Code
Private Shared Sub SendCallback(ar As IAsyncResult)
Try
' Retrieve the socket from the state object.
Dim handler As Socket = DirectCast(ar.AsyncState, Socket)
' Complete sending the data to the remote device.
Dim bytesSent As Integer = handler.EndSend(ar)
'trying to receive again - I added this after commenting out the below lines but am missing something.
Dim state As StateObject = DirectCast(ar.AsyncState, StateObject)
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
'The below lines are what was there, I tried to comment out and use the above lines trying to receive again but it does not work. I assume I am missing something simple but can not find anything useful. Any help would be appreciated.
'handler.Shutdown(SocketShutdown.Both)
'handler.Close()
Catch e As Exception
PubVars.ServerStatus = e.ToString
End Try
End Sub
I know I do not want to close the socket until all is sent but I am not sure what i am missing. I want to send the first file, then send back to the client a status update which all works well. Then when the client receives the status update, I want to send the next file and so on.
Android Code:
Socket socket = null;
try {
socket = new Socket("localhost", 11000);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
String FileName = "my.jpg";
String FilePath= Environment.getExternalStorageDirectory() + "/mydir/" + FileName;
File f= new File(FilePath);
byte[] data= readFileToByteArray(f);
String strbase64 = Base64.encodeToString(data, Base64.DEFAULT);
//I chose to pass the filename as part of my header string then parse it out on server
output.println("<HEADER>" + FileName + "</HEADER>" + strbase64 + "<EOF>");
output.flush();
InputStream in = socket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder returnString = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
returnString.append(line).append('\n');
}
Log.i("INPUT",returnString.toString());
//If true run the next one
//SEND NEW FILE
Log.i("NEXT","STARTING NEXT FILE");
FileName = "my2.png";
FilePath= Environment.getExternalStorageDirectory() + "/mydir/" + FileName;
f= new File(FilePath);
data= readFileToByteArray(f);
strbase64 = Base64.encodeToString(data, Base64.DEFAULT);
output.println("<HEADER>" + FileName + "</HEADER>" + strbase64 + "<EOF>");
output.flush();
in = socket.getInputStream();
r = new BufferedReader(new InputStreamReader(in));
returnString = new StringBuilder();
while ((line = r.readLine()) != null) {
returnString.append(line).append('\n');
}
Log.i("INPUT",returnString.toString());
//END ANOTHER FILE
output.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
I am developing in the Android. I found a sample code. It open the file by the following code:
private static final String TEST_DATA_FILE_NAME = "test.txt";
FileInputStream fin = activity.openFileInput(TEST_DATA_FILE_NAME);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
and use String text = br.readLine(); to read.
I use following code to get the file path:
File outFile =activity.getDatabasePath(MESH_DATA_FILE_NAME);
Log.i(TAG, "outFile.getPath() = " + outFile.getPath());
And it show the following log:
outFile.getPath() = /data/data/com.test.app.test/databases/test.txt
I want to get the test.txt and send to computer via some file manager App.
But I can not find the test.txt , I also can not find the above path.
Why I can not fine the file ?
How to get the test.txt file?
Thanks in advance.
If the file is on the SDcard you can read it
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "/somefolder/file.txt";
File myFile = new File(baseDir + File.separator + fileName);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
String filecontent = aBuffer;
myReader.close();
I'm developing an app in which I'm sending a .txt file from one end by attaching it with gmail. Everytime this file is sent, its name is data.txt. When this file is downloaded at the other end, on the first download its name is the same, i.e. data.txt. However, when another file is sent with the same name, the name of the file at the receiveing end becomes data-1.txt, data-2.txt etc. And because of this, I'm not able to read the proper file. Please could someone give me some suggestions to solve this problem? The sending and receiving code is given below: SEND
bSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
String toWrite = enterText.getText().toString();
FileOutputStream fos;
try {
String path = Environment.getExternalStorageDirectory().toString();
Log.v("path", path);
File myFile = new File("" + path + "/" + fileName + ".txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(toWrite);
Log.v("file written", toWrite);
myOutWriter.close();
fOut.close();
Uri u1 = null;
u1 = Uri.fromFile(myFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "MPPT Configuration Data");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
READ:
bRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/storage/sdcard0/download/" + fileName + ".txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
Log.v("read data", "" + aBuffer);
tvData.setText(aBuffer);
}catch (IOException e2) {
e2.printStackTrace();
}
}
});
I found a possible solution. I can link the file manager (external app) from where the user can pick out whichever file he wants to be read.
Thanks #greenapps fir the idea of displaying a list of files.
You can get all the file by using regex ,then process the file by following way:
1.if only one file found,read it;
2.if more than one file found, compare and read the file which last number is biggest
but this solution still has one problem,if has file data.txt and data-3.txt ,the file we want to read may become data-2.txt,but what we really read is data-3.txt.
Or,maybe you can get the file you want by judging file established time.
I have an sqlite database which is written to from a service running on windows(C++). I am now trying to read from this same sqlite database which contains some blob data. I have some code as follows:
String tileQuery = "SELECT * FROM '" + layerName + "' WHERE zoom_level=?";
Cursor tileCursor = database.rawQuery(tileQuery, new String[] {zoom_level});
if( tileCursor.moveToFirst() )
{
while( !tileCursor.isAfterLast() )
{
int tileRow = tileCursor.getInt(tileCursor.getColumnIndex("tile_row"));
int tileColumn = tileCursor.getInt(tileCursor.getColumnIndex("tile_column"));
byte[] tileData = tileCursor.getBlob(tileCursor.getColumnIndex("tile_data"));
//Write tile to file
String fileName = layerName + "_" + zoom_level + "_" + tileRow + "_" + tileColumn + ".jpeg";
try {
/*
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + TILE_STORAGE_PATH + "/" + fileName));
bos.write(tileData);
bos.flush();
bos.close();
*/
ByteBuffer bb = ByteBuffer.wrap(tileData);
bb.order(ByteOrder.LITTLE_ENDIAN);
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + TILE_STORAGE_PATH + "/" + fileName);
byte[] toWrite = new byte[bb.remaining()];
bb.get(toWrite, 0 , toWrite.length);
fos.write(toWrite);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
tileCursor.moveToNext();
}
}
As shown, I am attempting to write the blobs to disk as jpeg images. No matter what I do, the images appear to be corrupt, as in I cannot view them on any image viewer within android. The same images can be written to file on windows and viewed correctly, which made me think that it was an endianess issue(due to the fact that the blob was written to the database via a service running on windows). I have tried changing the byte order and writing to disk again, but I get the same result. Could anyone suggest what I might be doing wrong/missing. Any help is greatly appreciated.
To make this work there are a few different steps. Assuming your database connection is working and those are the correct columns you are looking in with your Cursor
(1) Convert the blob to a Bitmap. You can use the blob you get back, assuming you actually downloaded and stored it to your local database, as the byte[] you will decode.
Bitmap bm = BitmapFactory.decodeByteArray(tileData, 0 ,tileData.length);
(2) Create a new file in the approprite directory and write to that file. You can do that with something like the code below. The idea is to get the local directory
private void storeBitmap(Bitmap myBitmap){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/your_directory_name");
String fname = "your_file_name.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
If you want to add the images to gallery or you just want a different (and potentially easier) way to add the file, look into using MediaScanner which will add the files as though you took the picture with your camers
I'm trying to save and then load the files that I've just saved but I can't find it.
I know it is being saved because I can look at the cache size under the Manage Application screen for the app and see that the size goes up when I save the image.
This is the error I'm getting: java.io.FileNotFoundException: /data/data/com.xxxxx/files/5ec2d71d-8a99-4258-a33a-91f6f99b8f0e.jpg
Here is my code:
imageDir = new File(context.getCacheDir().getAbsolutePath());
String newName = UUID.randomUUID().toString() + ".jpg";
Bitmap bmp = ImageLoader.getInstance().getBitmap(e.getUrl());
Boolean r = imageDir.exists();
Boolean c = imageDir.canWrite();
String[] d = imageDir.list();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imageDir + "/" + newName));
bmp.compress(CompressFormat.JPEG, 90, out);
out.flush();
out.close();
d = imageDir.list();
FileInputStream fis = new FileInputStream(imageDir + "/" + newName);
ObjectInputStream ois = new ObjectInputStream(fis);
Bitmap b = (Bitmap) ois.readObject();
Ideas?
Context.openFileInput opens files within your app's data directory. What is the point of that call anyway? You already created a FileInputStream.