so Im trying to develop a "module/addon" system and I want to read a "module.json" file from all modules/addons loaded in a direcory. So I got the part with looping through the files and stuff. But I dont know how I can access that "module.json" file.
Here is what I tried:
try {
for (File file : this.modulesDir.listFiles()) {
if(file.getName().endsWith(".jar")) {
InputStream stream = new URLClassLoader(new URL[]{file.toURL()}).getResourceAsStream("./module.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
while((builder.append(reader.readLine())) != null);
reader.close();
stream.close();
System.out.println(builder.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
Alright! I fixed it by changeing the path of the file to module.json instead of /module.json
Heres the code:
try {
for (File file : this.modulesDir.listFiles()) {
if(file.getName().endsWith(".jar")) {
InputStream stream = new URLClassLoader(new URL[]{file.toURL()}).getResourceAsStream("module.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
builder.append(line);
}
System.out.println(builder.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
Related
I have may wifi2.txt file in my assets file directory in Android Studio. However, I keep getting a NULLPointException when I try to access it. My code is below: (Thanks so much in advance)
//CSV FILE READING
File file = null;
try {
FileInputStream is = new FileInputStream(file);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
String line;
Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] RowData = line.split(",");
LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
if (RowData.length == 4) {
mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Done with CSV File Reading
In Kotlin, we can achieve this :-
val string = requireContext().assets.open("wifi2.txt").bufferedReader().use {
it.readText()
}
File file = null;
try {
FileInputStream is = new FileInputStream(file);
Actually you are not using FileInputStream anywhere. Just use this piece of code
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
String line;
Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] RowData = line.split(",");
LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
if (RowData.length == 4) {
mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
Method to read a file FROM assets:
public static String readFile(AssetManager mgr, String path) {
String contents = "";
InputStream is = null;
BufferedReader reader = null;
try {
is = mgr.open(path);
reader = new BufferedReader(new InputStreamReader(is));
contents = reader.readLine();
String line = null;
while ((line = reader.readLine()) != null) {
contents += '\n' + line;
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
return contents;
}
Usage: String yourData = LoadData("wifi2.txt");
Where wifi2.txt is assumed to reside in assets
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
Reference
My solution using kotlin to load text from asset file
object AssetsLoader {
fun loadTextFromAsset(context: Context, file: String): String {
return context.assets.open(file).bufferedReader().use { reader ->
reader.readText()
}
}
}
use it like this:
val text = AssetsLoader.loadTextFromAsset(context, "test.json")
I have a problem and can't find a good solution to it. I need to read a textfile with large amount of data (file has 16MB). The file contains 12 columns with integer values in each one. Generally my problem is how to do this without freezing the app. I have my file in the assets folder of my project and I tried using something like this:
AssetManager assetManager = this.getAssets();
try {
InputStream inputStream = assetManager.open("3333.ecg");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
while ((str = bufferedReader.readLine()) != null) {
stringBuilder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
But app freezes. My goal is to get the data from each column and save it into an arraylist of integers. I'm looking for some advice.
Thanks in advance.
Use this to run it in background:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
AssetManager assetManager = this.getAssets();
try {
InputStream inputStream = assetManager.open("3333.ecg");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
while ((str = bufferedReader.readLine()) != null) {
stringBuilder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
I would like to print line by line the file located in some directory with:
private void readWeatherDataByColumn() {
FileInputStream is = null;
try {
is = new FileInputStream(sourceDirectory);
String line = "";
BufferedReader br = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Prints throwable details
e.printStackTrace();
}
}
I get the following output:
05-21 20:13:42.018 4170-4170/com.soialab.askaruly.camera_sensor I/System.out: ������ ftypisom������isomiso2avc1mp41������
Anyone has any clues?
This must be output
05-22 17:13:22.676 5955-5955/com.soialab.askaruly.camera_sensor I/System.out: 1,22:28:23,42,92,66,224,40,0.28,0.02,0.05
05-22 17:13:22.677 5955-5955/com.soialab.askaruly.camera_sensor I/System.out: 2,22:28:24,48,92,191,224,64,0.28,0.02,0.05
Add the below code where you want to read CSV file.
String csvFileString = readFile(selectedFile.getAbsolutePath()); // path of you selected CSV File
InputStream stream = null;
try {
stream = new ByteArrayInputStream(csvFileString.getBytes(StandardCharsets.UTF_8.name()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ReadCsv csv = new ReadCsv(stream);
List<String[]> results = new ArrayList<String[]>();
results = csv.read();
public static String readFile(String theFilePathString) {
String returnString = "";
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream((theFilePathString)), "UTF8"));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
returnString = stringBuilder.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return returnString;
}
ReadCsv.Class
public class ReadCsv {
InputStream in;
public ReadCsv(InputStream in) {
this.in = in;
}
public List<String[]> read() {
List<String[]> results = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
results.add(row);
}
} catch (IOException e) {
throw new RuntimeException("Error reading CSV File " + e);
} finally {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException("Error closing inputstream " + e);
}
}
return results;
}
}
Thank you for the comments and replies!
I figured out the problem. The string sourceDirectory was of the video file, not the original ".csv" text document. Therefore, some encoding problem occured, as mentioned by #TimBiegeleisen.
Now, it works totally fine with the same code. My bad, sorry...
I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)
I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I used following method to write data to a file in one android application
private void writeFileToInternalStorage() {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE)));
writer.write("Hello world!");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Then I tried to read that file from another android application using this method
private void readFileFromInternalStorage(){
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try
{
input = new BufferedReader(new InputStreamReader(openFileInput("myFile1.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null)
{
buffer.append(line + eol);
}
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(buffer.toString().trim());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (input != null)
{
try
{
input.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Second method can't read the file. I added read write permissions also, but it shows only blank screen. What can be the error and how can I correct that ??. I'm new to Android programming and need your help.
Thanks!
The problem is
openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE))
The documentation says:
This file is written to a path relative to your app within the
So the case is you are writing file in path relative to application 1 and trying to read it from
path relative to application 2.
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
Look below snippet to write file to SD card.
private void writeToSDCard() {
try
{
File file = new File(Environment.getExternalStorageDirectory(),
"filename");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello World");
writer.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Look below snippet to read file saved on SD card.
private void readFileFromSDCard() {
File directory = Environment.getExternalStorageDirectory();
// Assumes that a file article.rss is available on the SD card
File file = new File(directory + "/article.rss");
if (!file.exists()) {
throw new RuntimeException("File not found");
}
Log.e("Testing", "Starting to read");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Your best bet is to place it into the scdcard into something like /sdcard/Android/data/package/shared/