我正在尝试从文件中读取内容,但我找不到文件异常。
请帮帮我。我正在使用下面的代码。
File f = new File("C:/sample/welcome.txt"); //working
System.out.println("File path ="+f.getPath());
System.out.println("File name = "+f.getName());
System.out.println("File size = "+f.length());
String ret = "";
HttpURLConnection connection = null;
try {
int size = (int) f.getName().length();
byte[] data = new byte[size];
String _contrainerName1 ="/development";
// String content = new String("This is my first upload to dropbox");
//String fileName ="test17.txt";
try {
InputStream inputStream = new FileInputStream(f.getName());
if ( inputStream != null ) {
DataInputStream in1 = new DataInputStream(inputStream);
// InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in1));
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("login activity");
} catch (IOException e) {
e.printStackTrace();
System.out.println("login activity");
}
答案 0 :(得分:1)
如果您尝试在Windows文件系统中读取文件,则应使用双重反弹:
File f = new File("C:\\sample\\welcome.txt");
此外,您可以实例化直接传递File对象的FileInputStream
InputStream inputStream = new FileInputStream(f);
答案 1 :(得分:0)
要做的第一件事是检查C:\驱动器中是否确实存在该文件。
C:\ drive
C:/sample/welcome.txt
反斜杠是第一个提示:)
答案 2 :(得分:0)
try {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "location/of/filename.txt");
BufferedReader r = new BufferedReader(new FileReader(file));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
total.append('\n');
}
String ttt = total.toString();
TextView txt = (TextView)findViewById(R.id.txt);
txt.setText(ttt);
r.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
在android
中读取文件的确切代码答案 3 :(得分:0)
CommonsWire如何说,在Android C:
中并不存在。
您有 getExternalStorageDirectory
。
试试这个:
File myfile = new File(Environment.getExternalStorageDirectory() + File.separator + "myFile.txt");