如果文件不存在,则创建它并将字符串写入其中。如果确实如此,则将字符串附加到它。工作不正常

Posted

技术标签:

【中文标题】如果文件不存在,则创建它并将字符串写入其中。如果确实如此,则将字符串附加到它。工作不正常【英文标题】:If file does not exist, create it and write string to it. If it does then append string to it. Isn't working right 【发布时间】:2013-04-07 14:41:52 【问题描述】:

好的,我阅读了很多,并认为我已经解决了这个问题,但显然没有。我要做的是检查文件是否存在(在本例中为 heapFile.csv),如果不存在,则创建它,然后向其写入字符串。如果文件确实存在,那么我想将字符串附加到文件中。当我运行它时,我没有收到任何错误,尽管我确实收到警告说它无法创建文件,尽管它确实这样做了。但是,无论哪种情况,它都不会将字符串写入文件。我可能只是没有使用正确的语法或其他东西,但是在盯着这个看了几个星期之后,我看不到树木的森林并找到了问题。除了这个问题,我的程序运行良好,如果我能正常工作,我终于可以完成这个。非常感谢任何帮助。

这是 java 文件。我认为文件创建/写入位在哪里很清楚。

package com.loch.meaptracker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.google.ads.*;


import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TimePicker;

public class MainActivity extends Activity implements OnSeekBarChangeListener 

private SeekBar happyBar, energyBar, anxietyBar, painBar;
private EditText noteField;
private DatePicker dPick;
private TimePicker tPick;
@SuppressWarnings("unused")
private Button enterButton;
private int happyValue = 4, energyValue = 4, anxietyValue = 4,
        painValue = 4;
private static final String TAG = "heapApp";
private String Mood = "Blah";
private AdView adView;
final Context context = this;

@Override
protected void onCreate(Bundle savedInstanceState) 
    try 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create the adView
        adView = new AdView (this, AdSize.BANNER, "a15138b1a7adad2");

        // Lookup your RelativeLayout assuming it's been given the attribute android:id="@+id/AdRelativeLayout
        RelativeLayout layout = (RelativeLayout)findViewById(R.id.AdRelativeLayout); 

        // Add the AdView to it
        layout.addView(adView);

        // Initiate a generic request to load it with an ad
        adView.loadAd(new AdRequest());

        // bars
        happyBar = (SeekBar) findViewById(R.id.happinessBarID);
        happyBar.setOnSeekBarChangeListener(this);
        energyBar = (SeekBar) findViewById(R.id.energyBarID);
        energyBar.setOnSeekBarChangeListener(this);
        anxietyBar = (SeekBar) findViewById(R.id.anxietyBarID);
        anxietyBar.setOnSeekBarChangeListener(this);
        painBar = (SeekBar) findViewById(R.id.painBarID);
        painBar.setOnSeekBarChangeListener(this);
        // end bars
        dPick = (DatePicker) findViewById(R.id.datePicker1);
        tPick = (TimePicker) findViewById(R.id.timePicker1);
        noteField = (EditText) findViewById(R.id.noteTextFieldID);
        enterButton = (Button) findViewById(R.id.enterButtonID);
     catch (Exception onCreateException) 
        Log.e(TAG, "Exception received", onCreateException);
    


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;


// Bar listener methods
@Override
public void onProgressChanged(SeekBar arg0, int barValue, boolean hFromUser) 
    try 

        switch (arg0.getId()) 
        case R.id.happinessBarID:
            happyValue = barValue + 1;
            break;
        case R.id.energyBarID:
            energyValue = barValue + 1;
            break;
        case R.id.anxietyBarID:
            anxietyValue = barValue + 1;
            break;
        case R.id.painBarID:
            painValue = barValue + 1;
            break;
        
        String debugBarValue = "Happy is " + happyValue + ", Energy is "
                + energyValue + ", Anxiety is " + anxietyValue
                + ", Pain is " + painValue + ".";
        System.out.println(debugBarValue);

     catch (Exception BarValueException) 
        Log.e(TAG, "Exception received", BarValueException);
    



@Override
public void onStartTrackingTouch(SeekBar happyBar) 
    // TODO Auto-generated method stub



@Override
public void onStopTrackingTouch(SeekBar happyBar) 
    // TODO Auto-generated method stub



// end Bar listener methods

// Enter Button listener Method

public void dialogPop(View v) 
    try 
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);

        // set Title
        alertDialogBuilder.setTitle("title");

        // set dialog message
        alertDialogBuilder.setMessage("You entered: " + getMood())
                .setCancelable(false).setPositiveButton("Okay",
                // When Okay button clicked the write mood string to file
                        new DialogInterface.OnClickListener() 
                            public void onClick(DialogInterface dialog,
                                    int id) 
                                try 
                                    // This is the string that should be
                                    // written to file
                                    String data = getMood();
                                    // This is the file that should be
                                    // written to
                                    File heapFile = new File(Environment.getExternalStorageDirectory(), "heapFile.csv");

                                    // if file doesn't exists, then create
                                    // it
                                    if (!heapFile.exists()) 
                                        heapFile.createNewFile();
                                        FileWriter heapFileWritter = new FileWriter(
                                                heapFile.getName(), true);
                                        BufferedWriter heapBufferWritter = new BufferedWriter(
                                                heapFileWritter);
                                        heapBufferWritter.write(data);
                                        heapBufferWritter.close();

                                        System.out.println("Done");
                                    

                                    // true = append file
                                    FileWriter heapFileWritter = new FileWriter(
                                            heapFile.getName(), true);
                                    BufferedWriter heapBufferWritter = new BufferedWriter(
                                            heapFileWritter);
                                    heapBufferWritter.write(data);
                                    heapBufferWritter.close();

                                    System.out.println("Done");

                                 catch (IOException e) 
                                    e.printStackTrace();
                                
                            

                        )
                // If they press either the cancel button or the back button
                // on their device (Same thing) then close the dialog and
                // give the user a chance to change what they've entered
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() 

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int id) 
                                // TODO Auto-generated method stub
                                dialog.cancel();
                            
                        );

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
     catch (Exception buttonListenerException) 
        Log.e(TAG, "Exception received", buttonListenerException);
    
    return;


public String getMood() 
    try 
        int month = dPick.getMonth();
        int day = dPick.getDayOfMonth();
        int year = dPick.getYear();
        int minute = tPick.getCurrentMinute();
        String moodAntePost = "AM";
        boolean hourType = tPick.is24HourView();
        int moodHour = tPick.getCurrentHour();
        if (hourType == false && moodHour > 12) 
            moodHour = (moodHour - 12);
            moodAntePost = "PM";
         else if (hourType == false && moodHour <= 0) 
            moodHour = 12;
         else 
        
        String noteText = noteField.getText().toString();
        Mood = "Happiness," + happyValue + ",Energy," + energyValue
                + ",Anxiety," + anxietyValue + ",Pain," + painValue
                + ",Date," + month + "/" + day + "/" + year + ",Time,"
                + moodHour + ":" + minute + "," + moodAntePost + ",Note,"
                + noteText;
        System.out.println(Mood);
     catch (Exception getMoodException) 
        Log.e(TAG, "Exception received", getMoodException);
    

    return Mood;



编辑了我的问题以包含清单,以便您可以查看我拥有的权限。我认为它是正确的,但我不确定......

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loch.meaptracker"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.loch.meaptracker.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.google.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>

</manifest>

【问题讨论】:

快速提问,您是否添加了WRITE_EXTERNAL_STORAGEREAD_EXTERNAL_STORAGE 的权限? 哦,对了!让我编辑并将我的清单包含在问题中。虽然我认为我做的没错。 我实际上不需要包含读取外部存储的权限,因为我实际上并不需要相关文件的内容。反正还没有。当我包含一些我计划的其他功能时,我将需要在该程序的更高版本中这样做。 【参考方案1】:

使用这个:

 String file = heapFile.getAbsolutePath();
 FileWriter heapFileWritter = new FileWriter(file, true);

getName() 只会给你文件的名称。但是您需要为 FileWriter 提供绝对路径。

【讨论】:

好吧,你的建议奏效了,但由于某种原因它写了两次字符串。 >_ facepalm 我是个白痴。我现在明白为什么它做了两次。非常感谢。我想这会完成它。 对于任何阅读本文的人来说,这仅仅是因为我忽略了将 if do this stuff 之后的代码包装在 else 中。一旦我这样做了,它就完美地工作了。

以上是关于如果文件不存在,则创建它并将字符串写入其中。如果确实如此,则将字符串附加到它。工作不正常的主要内容,如果未能解决你的问题,请参考以下文章

MATLAB。写入文本文件或创建它,如果它不存在。将图形保存在目录中,如果不存在则创建它

fopen参数

文件内容操作

Java以缓冲字符流向文件写入内容(如果文件存在则删除,否则先创建后写入)

用shell脚本写出检测/tmp/size.log文件,如果存在显示它的内容,不存在则创建一个文件将创建时间写入

如果文件不存在,则创建一个文件