android: FileOutputStream Doesn't work - java

I try to make TCP-Sock program, and this is simple file recv program.
and now, i get some problem.
i think my client program's FileOutputStream class doesn't work.
below code is what i've made.
package kr.ac.cbnu.incping.tcp_cloud;
public class DownActivity extends Activity {
public static int contentNum;
public static String body=new String();
public static String fName=new String();
public static int fSize;
public static synchronized String getFilePath(String userID, String fName)
{
String sdcard = Environment.getExternalStorageState();
File file = null;
if ( !sdcard.equals(Environment.MEDIA_MOUNTED))
{
// SDcard isn't mount
file = Environment.getRootDirectory();
}
else
{
// SDcard is mount
file = Environment.getExternalStorageDirectory();
}
String dir = file.getAbsolutePath() + String.format("/tcp_cloud/%s",userID);
String path = file.getAbsolutePath() + String.format("/tcp_cloud/%s/%s",userID,fName);
file = new File(dir);
if ( !file.exists() )
{
// Make directory if dir doesn't exist
file.mkdirs();
}
// return File Path;
return path;
}
public void connect()
{
try{
Socket socket=new Socket(MainActivity.servIP, MainActivity.servPort);
DataOutputStream dos;
DataInputStream dis;
dis=new DataInputStream(socket.getInputStream());
dos=new DataOutputStream(socket.getOutputStream());
byte[]flag=new byte[3];
byte[]num=new byte[1];
byte[]uID=new byte[17];
String path=new String();
path=getFilePath(LoginActivity.usrName,fName);
File f=new File(path);
flag="05".getBytes("EUC_KR");
num=Integer.toHexString(contentNum).getBytes("EUC_KR");
uID=LoginActivity.usrName.getBytes("EUC_KR");
dos.write(flag);
dos.flush();
dos.write(num);
dos.flush();
dos.write(uID);
dos.flush();
FileOutputStream fos=new FileOutputStream(f);
Toast.makeText(getApplicationContext(),path,Toast.LENGTH_LONG).show();
BufferedOutputStream bos=new BufferedOutputStream(fos);
dos=new DataOutputStream(bos);
int len;
int size = 512;
byte[] data = new byte[size];
while ((len = dis.read(data,0,size))!=-1)
{
dos.write(data);
}
dos.flush();
Toast.makeText(getApplicationContext(),path+" saved",Toast.LENGTH_LONG).show();
dos.close();
bos.close();
fos.close();
dos.close();
dis.close();
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_down);
String title=new String();
if(contentNum==0)
title=LoginActivity.title1;
else if(contentNum==1)
title=LoginActivity.title2;
else if(contentNum==2)
title=LoginActivity.title3;
else if(contentNum==3)
title=LoginActivity.title4;
else if(contentNum==4)
title=LoginActivity.title5;
TextView bodytit=(TextView) findViewById(R.id.bodyTitle);
TextView bodydat=(TextView) findViewById(R.id.bodyBody);
Button filedat=(Button) findViewById(R.id.filename);
bodytit.setText(title);
bodydat.setText(body);
filedat.setText(fName+"(size: "+fSize+")");
filedat.setOnClickListener(new OnClickListener(){
public void onClick(View v){
connect();
}
});
}}
and this code is troubled code
FileOutputStream fos=new FileOutputStream(f);
Toast.makeText(getApplicationContext(),path,Toast.LENGTH_LONG).show();
BufferedOutputStream bos=new BufferedOutputStream(fos);
dos=new DataOutputStream(bos);
toast message is just prob message. when placed toast above of the FOS, toast working well.
but toast isn't working in that position
i can't solve this problem. please, somebody help me..T.T
*i'm not english language area's person. so my english isn't nice sentence. i'm sorry about that;)

In my case FileOutputStream and OutputStreamWriter is not works.
So I was changed File classes to this.
FileWriter fileOut = new FileWriter(fileFullPath, false);
String jsonString = new Gson().toJson(json);
fileOut.write(jsonString);
fileOut.close();

Related

How to remove specific line from the file

I am trying to delete a specific line from a file, but when I run this, it returns me all the files, deleted. More specific i have a favorite button at a video fragment and i want when user press it ,to write the title of video in file (already done) and when unpress it to delete it....
my.java class is:
private void writeToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/config.txt");
FileOutputStream fos = new FileOutputStream(file,true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (!file.exists()) {outputStreamWriter.write(g);}
outputStreamWriter.append("\n"+g +"\n");
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private void deleteToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
outputStreamWriter.write(text.toString());
}
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.favorite:
if(showingFirst==true) {
Context context = getActivity();
CharSequence text = "Added to Favorites";
int duration = Toast.LENGTH_SHORT;
item.setIcon(R.drawable.heart_off);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
writeToFile(title,context);
showingFirst=false;
} else {
Context context = getActivity();
CharSequence text = "Deleted from Favorites";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
deleteToFile(title,context);
item.setIcon(R.drawable.heart_wh);
showingFirst=true;
}
break;
case R.id.home:
Intent k=new Intent(getActivity(),MainActivity.class);
Log.i(TAG, "onNavigationItemSelected: ");
startActivity(k);
break;
}
return false;
}
So, problem lies at below line of codes where you are trying to open file for Read and Write simultaneously
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
Instead, I would suggest you to read your file completely and then at the end you should write to the file (overwrite).
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
//start writing from here
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
outputStreamWriter.write(text.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
}
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
This line:
FileOutputStream fos = new FileOutputStream(file);
resets contents of the file (ie replaces it with empty file). I recommend you add logging and/or debug your code so you will have a better understanding of what is going on.

Issue In Zipping Pcap Files

I am generating pcap files and need to zip it. Currently i am able to generate and store the pcap file in local storage.
for zipping i am using below code:
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
byte[] buffer = new byte[1024];
try {
zipFilePath = urls[0];
FileOutputStream fos = new FileOutputStream(zipFilePath + ".zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(urls[1]);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(zipFilePath);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
//remember close it
zos.close();
return zipFilePath + ".zip";
} catch (IOException ex) {
ex.printStackTrace();
return "";
}
}
I am getting file not found exception at FileOutputStream fos = new FileOutputStream(zipFilePath + ".zip");

Android copy file from internal storage to external

I am trying to Copy file from internal memory card to external memory card
By googling i found this answer
try {
InputStream in = new FileInputStream("/storage/sdcard1/bluetooth/file7.zip"); // Memory card path
File myFile = new File("/storage/sdcard/"); //
OutputStream out = new FileOutputStream(myFile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
session.showToast("file copied sucessfully");
} catch (FileNotFoundException e) {
showToast(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
showToast(e.getMessage());
e.printStackTrace();
}
its work for internal move to internal or external storage to external
but cross transferring do not work its throws an error Erofs read only file system
Try some thing like this:
new FileAsyncTask().execute(files);
and
// AsyncTask for Background Process
private class FileAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ActivityName.this, "Your Title", "Loading...");
}
#Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileToSDCard(files.get(i));
} return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
// Function to copy file to the SDCard
public void copyFileToSDCard(String fileFrom){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFrom);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/MyProject", fileFrom));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}
Try this, Replace this line:
File myFile = new File("/storage/sdcard/");
with:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File myFile = cw.getDir("imageDir", Context.MODE_PRIVATE);
Check this link, may be helpfull: click here

Sockets, sent pdf file always arrives zero bytes size

I'm sending a pdf file from android tablet client to Java app running on Windows 7. The file always arrives as a size of zero bytes. what is the problem here?
Before the pdf file was sent from client to server, the size of the file as long value is sent from client to server, this size is correct and always arrives to the server. For the pdf file, I'm using for this test the size is 566718 bytes.
How can I get the pdf file to arrive as the correct size?
Server code
public class Server {
ServerSocket serverSocket;
Socket socket;
boolean runner = true;
Server() throws IOException{
serverRunner();
System.out.println("server constructor started");
} // Server() constructor
public void serverRunner() throws IOException {
System.out.println("serverrunner started");
try {
serverSocket = new ServerSocket(6789, 100);
runner = true;
while (runner) {
socket = serverSocket.accept();
MultiThreader multi = new MultiThreader(socket);
Thread t = new Thread(multi);
t.start();
} // while runner
} catch (IOException ex) {
}
} // serverRunner()
} // class Server
public class MultiThreader implements Runnable {
Socket socket;
public int fileSizeFromClient;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
DataInputStream dis = null;
DataOutputStream dos = null;
public MultiThreader(Socket socket){
System.out.println("print out from multithreader class");
this.socket = socket;
} // multiThreader
#Override
public void run() {
System.out.println("multi threader started");
// action #1 read file from client =====================================
// transfer.pdf read this file sent from android device to this computer
int bufferSize = 0;
try {
bis = new BufferedInputStream(socket.getInputStream());
dis = new DataInputStream(bis);
fileSizeFromClient = dis.readInt();
System.out.println("file size from client is " + fileSizeFromClient);
File fileDirectory = new File("C:/DOWNLOAD/");
if (!fileDirectory.exists()) {
fileDirectory.mkdir();
}
File file = new File("C:/DOWNLOAD/transfer.pdf");
file.createNewFile();
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
dos = new DataOutputStream(bos);
byte[] buffer = new byte[fileSizeFromClient];
int totalBytesRead = 0;
while(totalBytesRead < fileSizeFromClient){
int bytesRemaining = fileSizeFromClient = totalBytesRead;
int bytesRead = dis.read(buffer, 0, (int) Math.min(buffer.length, bytesRemaining));
if(bytesRead == -1) {
break;
} else {
dos.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
} // while
} catch (IOException ex) {
Logger.getLogger(MultiThreader.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
// socket.close();
} catch (IOException ex) {
Logger.getLogger(MultiThreader.class.getName()).log(Level.SEVERE, null, ex);
}
}
} // run
} // MultiThreader
client code
public class MainActivity extends Activity implements Runnable {
TextView textViewOne;
Button buttonOne;
Socket socket;
private String serverIP = "192.XXX.X.X";
FileInputStream fis;
FileOutputStream fos;
private File file;
DataInputStream dis;
DataOutputStream dos;
BufferedInputStream bis;
BufferedOutputStream bos;
long length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewOne = (TextView) findViewById(R.id.textView1);
buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread myThread = new Thread(MainActivity.this);
myThread.start();
}
});
} // oncreate
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
textViewOne.setText("run method started");
}
});
try {
socket = new Socket(InetAddress.getByName(serverIP), 6789);
if (socket == null) {
return;
} else {
MainActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
textViewOne.setText("connected");
}
});
}
file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "transfer.pdf");
length = file.length();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
bos = new BufferedOutputStream(socket.getOutputStream());
dos = new DataOutputStream(bos);
dos.writeInt((int) length); // sends the length as number bytes is file size
int count = 0;
byte[] buffer = new byte[(int) length];
while ((count = bis.read(buffer)) > 0)
{
bos.write(buffer, 0, count);
}
bos.flush();
bis.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // mainactivity
This is the problem, I believe.
int bytesRemaining = fileSizeFromClient = totalBytesRead;
That's doing two assignments, so you're assigning 0 to fileSizeFromClient immediately, and exiting the loop.
You meant:
int bytesRemaining = fileSizeFromClient - totalBytesRead;
That's a pretty subtle typo, and you were unlucky that it's a typo which still resulted in valid code :(
Given that you're closing the socket immediately anyway though, it's not clear why you're sending the file size first. Your code could be simpler if you just had the same "copy from an input stream to an output stream until the input runs out of data" at both the client and the server, just from a FileInputStream to a Socket's OutputStream at the client, and the Socket's InputStream to a FileOutputStream (possibly with a buffering wrapper) at the server.
I'd also recommend closing all streams - if you're using Java 7, you can do this simply using a try-with-resources statement; in earlier versions you should close streams in finally blocks.
- By rule of thumb, always close the Streams after writing/reading to and from it.
- Close the Stream at Server side.
- Use Socket with InputStream and Scanner for hassle free data transfer between socket. (Thats what i felt, experimenting with sockets.)

saving a text in the notepad in android

I just want to ask about my code whether it's right, because I can't load the text in my name.txt file.
Also I just want to know how to save the input text in my name.txt file.
load.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick
(View arg0) {
try{
StringBuffer sb=new StringBuffer();
FileInputStream fis=con.openFileInput("name.txt");
DataInputStream dis=new DataInputStream(fis);
String text=null;
while((text=dis.readLine())!=null)
sb.append(text+"\n");
dis.close();
et1.setText(sb.toString());
}catch
(IOException e){
Toast.makeText(con, "Could not find", Toast.LENGTH_LONG).show();
}
}
});
If you want to write data to file
static protected void writeToFile(String strToWrite)
{
try
{
BufferedWriter out = new BufferedWriter(new FileWriter("name.txt", true));
out.write(strToWrite);
out.close();
}
catch (IOException e) { e.printStackTrace();}
}
The code you have written is to read data from an existing file not to write in the file.
try
{
File file1 = new File(Environment.getExternalStorageDirectory() + "/dir/", "filename.extension");
FileWriter fw1 = new FileWriter(file1.getAbsoluteFile());
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write("Stringtowritetofile");
bw1.close();
}

Categories

Resources