Skip to content

Instantly share code, notes, and snippets.

@operando
Last active December 30, 2015 00:18
Show Gist options
  • Save operando/7748154 to your computer and use it in GitHub Desktop.
Save operando/7748154 to your computer and use it in GitHub Desktop.
Android4.4でBufferedReaderがファイルの最後の行に、無駄な改行を入れているとそのまま読み込んで、readLineでnullが返ってくるコード。
package com.example.bufferedreader_test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
/* BufferedReaderTest.txtの中身(----------内。最後に無駄な改行を入れる)
-------------------------------------
1test
2test
3test
4test
5test
6test
7test
8test
-------------------------------------
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
AssetManager as = getResources().getAssets();
InputStream input = null;
FileOutputStream output = null;
// assets内のファイルをfilesにコピーする
input = as.open("BufferedReaderTest.txt");
output = openFileOutput("BufferedReaderTest.txt", Context.MODE_PRIVATE);
int DEFAULT_BUFFER_SIZE = 1024 * 4;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
File packageDir = getFilesDir();
String connectionFilePath = packageDir.toString() + "/BufferedReaderTest.txt";
try {
File paramString = new File(connectionFilePath);
BufferedReader bufferedReader = new BufferedReader(new FileReader(paramString));
while (bufferedReader.ready()) {
String str = bufferedReader.readLine();
Log.d("MainActivity",str);
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment