Android File.mkdirs()在尝试在sdcard中创建目录时返回false

时间:2018-02-01 03:21:37

标签: android storage android-sdcard

我知道在Stackoverflow中这是一个很多次被问到的问题,我已经看到了这些问题。答案建议检查权限,重新启动设备,检查父目录是否存在等。我尝试了所有这些,但仍然无法正常工作。

我在清单中指定了Manifest.permission.WRITE_EXTERNAL_STORAGE权限。

以下是我的代码。

        File newFile = new File(parent.getCanonicalPath() + "/" + dirName + "/");
        if(!newFile.exists()){
            boolean created = newFile.mkdirs();
            if(!created){
                int permission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                boolean permissionGranted = (permission == PackageManager.PERMISSION_GRANTED);
                Log.e(getClass().getSimpleName(), "Could not create directory " 
                        + ", Parent exists : " + parent.exists()
                        + ", Parent Dir writable : " + parent.canWrite()
                        + ", Permission granted : " + permissionGranted);

            }
        }

并打印日志

Could not create directory, Parent exists : true, Parent Dir writable : true, Permission granted : true

我通过其TreeUri获得了sdcard的写权限,然后我将树uri转换为实际路径以将其与File类一起使用。

我的minSdkVersion是19,targerSdkVersion是25

我做错了什么?

编辑:

我尝试了以上所有建议,但都失败了。现在,我使用DocumentFile解决了这个问题。我现在可以创建新的目录和文件。但我仍然不确定File发生了什么。谁能告诉我发生了什么?

我做了测试,

设备:联想A2010-A

Android版:5.1

3 个答案:

答案 0 :(得分:0)

替换

export default class MatchView extends Component {

	state = {
		matches: null,
		leagueName: null
	}

	componentWillMount = () => {

		this.getLeagueNames();
	}//end componentwwillMOunt

	// componentDidMount = () => {
	// 	console.log("league_array", this.state.leagueName)

	// }
	
	getLeagueNames = () => {
			let leagueArray = [];

			fetch(`https://apifootball.com/api/?action=get_leagues&APIkey=42f53c25607596901bc6726d6d83c3ebf7376068ff89181d25a1bba477149480`)
				.then(res => res.json())
					.then(leagues => {
						leagues.map(function(league, id){
							leagueArray = [...leagueArray, league]
						})//end .map
								this.setState({
									leagueName: leagueArray
								});	
					})
	}// end getLeagueNames

	getMatches = (leagueID) => {
		let LeagGamesArray = [];
		console.log('working')
		fetch(`https://apifootball.com/api/?action=get_events&from=2016-10-30&to=2016-11-01&league_id=${leagueID}&APIkey=42f53c25607596901bc6726d6d83c3ebf7376068ff89181d25a1bba477149480`)
					 .then(res => res.json())
					 	.then(fixtures => {

					 		LeagGamesArray = [...LeagGamesArray, fixtures]

					 	**	this.setState({
					 			matches: LeagGamesArray
					 		}) ** Setting the state here dosent work, just keeps running the code over and over again.**strong text**    					 			
					 	})
					 		
					}
					
					//console.log(this.state.matches)	
						
						//console.log(this.state.matches)
						//console.log(this.state.matches)
	

	renderItem = () => {
		if(this.state.leagueName != null){
		 		return this.state.leagueName.map(function(league){
		 			
		 			let leagueID = league.league_id
		 			let fix = this.getMatches(leagueID)
		 			//console.log(fix)
				
					return (
						<LeagueName key={league.country_id} league={league}/>
					)
					
				}.bind(this))//end maps..We .bind(this) b/c we want to change the meaning of this. We first use it in the .map function, but we also want to use this to call the getMacthes function.
			} else {
		 		return null;
			}
	}//end renderItem

	

	render(){
		return (
			<ScrollView>
  				{this.renderItem()}
  			</ScrollView>	  		
		)
	}
}

 boolean created = newFile.mkdirs();

答案 1 :(得分:0)

您不应使用getCanonicalPath并使用getAbsolutePath代替。以下是我创建新文件夹的方法:

File newFile = new File(parent,dirName);
if(!newFile.exists()){
        boolean created = newFile.mkdirs();
}

答案 2 :(得分:0)

将parent.getCanonicalPath()替换为Environment.getExternalStorageDirectory()

File myDirectory = new File(Environment.getExternalStorageDirectory(), dirName);

if(!myDirectory.exists()) {

//create file if not generated                                 
myDirectory.mkdirs();

}else { 
//not created file
}