我已经创建了一个Android应用程序并在模拟器上调试它,但它给了我一个异常android.os.NetworkOnMainThreadException
。
下面是远程访问数据的java
代码。
String filepath = datapath + "/tessdata/eng.traineddata";
// AssetManager assetManager = getAssets();
URL url = new URL("http://192.168.2.52/tessdata/eng.traineddata");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
// assetManager.open("tessdata/eng.traineddata");
InputStream instream = connection.getInputStream();
OutputStream outstream = new FileOutputStream(filepath);
byte[] buffer = new byte[1024];
int read;
while ((read = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, read);
}
outstream.flush();
outstream.close();
instream.close();
File file = new File(filepath);
if (!file.exists()) {
throw new FileNotFoundException();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
我在AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />