gpt4 book ai didi

java - 安卓工作室 : file written to another directory

转载 作者:行者123 更新时间:2023-12-04 10:47:40 26 4
gpt4 key购买 nike

我正在使用一个应用程序创建一个 csv 文件,然后我想导出并在手机上阅读。但是,我将其保存到的位置不可见,并且难以传输。

有没有办法将其保存到更容易访问的位置,例如电话上的/documents ?

(我对 Java 很陌生,如果这是一个明显的问题,我很抱歉)

谢谢!

public void submit(View v)
{
String nline = System.getProperty("line.separator");
String fname = firstName.getText().toString() + ",";
String sname = surname.getText().toString() + ",";
String gender = genderSpin.getSelectedItem().toString() + ",";
String eaddress = email.getText().toString() + ",";
String mnum = mobile.getText().toString() + ",";
String fos = course.getText().toString() + ",";
String prole = proleSpin.getSelectedItem().toString();
FileOutputStream file = null;

if(fname.length() <= 1 || sname.length() <= 1 || eaddress.length() <= 1){
Toast.makeText(this, "Please enter all mandatory fields", Toast.LENGTH_SHORT).show();
}
else {
try {
file = openFileOutput(fileName, MODE_APPEND);
file.write(fname.getBytes());
file.write(sname.getBytes());
file.write(gender.getBytes());
file.write(eaddress.getBytes());
if (mnum.length() < 11) {
mnum = "null,";
file.write(mnum.getBytes());
}
if (fos.length() <= 1) {
fos = "null,";
file.write(fos.getBytes());
}
file.write(prole.getBytes());
file.write(nline.getBytes());

firstName.getText().clear();
surname.getText().clear();
genderSpin.setSelection(0);
email.getText().clear();
mobile.getText().clear();
course.getText().clear();
proleSpin.setSelection(0);
Toast.makeText(this, "Successfully Submitted", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

最佳答案

先加WRITE_EXTERNAL_STORAGE到您的 list 文件。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

现在您需要请求许可,您可以这样做。


if(!checkPermission()){
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
WRITE_PERMISSION);
}

}
else {
// Permission already granted
}


授予权限后,您可以保存文件。

以下是工作 MainActivity.class
 package co.introtuce.nex2me.writefle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

public static final int WRITE_PERMISSION=0xff;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.mid);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermission();
}
});
}

public void requestPermission(){
if(!checkPermission()){
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
WRITE_PERMISSION);

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}

}
else {
afterPermisiion();
}
}
public boolean checkPermission(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
return false;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == WRITE_PERMISSION){
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Permisiion Granted
afterPermisiion();
return;
}

}
requestPermission();

}

public void afterPermisiion(){
submit();
}

public boolean saveFile(String csv_contents, Context context){
OutputStream outputStream = null;
try{
File root = Environment.getExternalStorageDirectory();
if(root == null){
Log.d("SAVE_PHONE", "Failed to get root");
return false;
}

// create a directory
File saveDirectory = new File(root,"appName/files/csv" );
// create direcotory if it doesn't exists

// create direcotory if it doesn't exists
if(!saveDirectory.exists()) if ( !saveDirectory.mkdirs()){
Toast.makeText(context,"sorry could not create directory"+saveDirectory.getAbsolutePath(), Toast.LENGTH_LONG).show();
return false;
}

outputStream = new FileOutputStream( saveDirectory + "myfile.csv"); // filename.png, .mp3, .mp4 ...
if(outputStream != null){
Log.e( "SAVE_PHONE", "Output Stream Opened successfully");
}

byte[] bytes = csv_contents.getBytes();
outputStream.write( bytes, 0, bytes.length );
outputStream.close();
return true;

}catch (Exception e){
Log.d("EXCEPTION_IN",e.toString());
return false;
}

}
public void submit()
{
String nline = System.getProperty("line.separator");
String fname = "Name" + ",";
String sname = "Surname" + ",";
String gender = "gn" + ",";
String eaddress = "email" + ",";
String mnum = "num" + ",";
String fos = "fos" + ",";
String prole = "prole";
FileOutputStream file = null;

if(fname.length() <= 1 || sname.length() <= 1 || eaddress.length() <= 1){
Toast.makeText(this, "Please enter all mandatory fields", Toast.LENGTH_SHORT).show();
}

String csv_contents = nline+""+fname+sname+gender+eaddress+mnum+fos+prole;
if(saveFile(csv_contents,this)){
//File has saved
// DO something
Toast.makeText(this,"File has been saved",Toast.LENGTH_LONG).show();
}
else{
//Could not save file
// DO something
}
}

}



这会将 cvs 文件保存在 FileManager 中,如 /storage/emulated/0/appName/files/csv地点。您可以修改此位置。

关于java - 安卓工作室 : file written to another directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59627011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com