Libgdx file handle.. reading a single line - java

I am trying to save and load files on a project that is coded on libgdx. Which means that i cant use a buffered reader because android wont read it.. and i cant move the project to android because it has to be in the core... after days and days or understanding all.. now i am trying File handing which should work right?? but i cant get it to read line by line.. it puts all the text in on string.. Help plzz.. also is my understanding correct and saving and loading is waaaay more complicated than it should be?? here is the code..
FileHandle handle = Gdx.files.local("words.txt");
String text = handle.readString();
words.add(text);

There are several ways to read this line by line. When your reading a file in using the LibGDX FileHandle API which include strings, byte arrays and into various readers; there are several ways to read the data in. I am assuming you have some form of dictionary in this file, with the words in a list separated by newlines? If this is the case you can take your existing string and split on the new line terminator.
FileHandle handle = Gdx.files.local("words.txt");
String text = handle.readString();
String wordsArray[] = text.split("\\r?\\n");
for(String word : wordsArray) {
words.add(word);
}
There's only really two newlines (UNIX and Windows) that you need to worry about.
FileHandle API

This is to all of you out there new to saving and loading and tired of looking for answers.. let me save u the trouble and days of research...
If you start a project in libgdx and want to save load on android.. Do not follow the buffered reader or inputstreamer or any of these tutorials THEY WILL NOT WORK because for some reason android cannot read inside the assest folder.. it will work on ur desktop version only..
if you are using android studios alone then go ahead with the try catch buffered or file or inputstreamer..
Also the Context.. asset manager.. and that route WILL NOT WORK because the project has to be in your android folder not core to use these libraries..
ELSE FOLLOW THE ABOVE METHOD..
classpath.. internal.. external .. or local ... depending on where you store ur file!!!.. your welcome

String str ="";
StringBuffer buf = new StringBuffer();
FileHandle file = Gdx.files.internal("text.txt");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(file.read()));
if (is != null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
} finally {
try { is.close(); } catch (Throwable ignore) {}
}

Related

How to use input from a java code and transfer it into an external application (as well as retrieving output)?

I'm actually not that great and am relatively new at Java. I wish to receive input from the user, and want to input this data into an external application.
This application processes the data and provides an output. I wish to retrieve this output using the Java code.
I have attempted in doing this but, I haven't got the slightest idea on how to start this script.
Nothin' on the internet seems to answer this question. If you have any idea or any new functions that can be useful, please help me in doing so.
Since I'm starting from ground zero, any help is appreciated.
Thanks so much.
To communicate with an external application you need to first define the communication way. For example:
Will this application read the output from a file?
If that statement it's true, then you need to learn serialization:
Will this application read the input from the standard output (like a command-line application)
If that statement it's true then you need to send with System.out.print().
Will this application get the data over HTTP.
Then you need to learn about REST and or RPC architectures.
Assuming that it will be a command-line application, then you could use something like this:
public class App
{
public static void main(String... args)
{
// You need to implement your business logic here. Not just print whatever the user passes as arguments of the command-line.
for(String arg : args)
{
System.out.print(arg);
}
}
}
There's a lot going on here but I'll suggest an example for each part of this question and assume this is just going to be written in Java, and suggesting an iterative design/development approach.
receive input from the user::getting arguments from the command line can work, but I think most users want to use familiar user interfaces like excel to input large amounts of data. Have them export files to .csv or look into reading excel files directly with apache poi. The latter is not for beginners, but not terrible to figure out or find examples. The former should be easy to figure out if you look into reading files and splitting them line by line on the delimiter. Here's an example of that:
try (BufferedReader reader = new BufferedReader(new FileReader(new File("user_input.csv"))) {
String currentLine = reader.readLine();
while (currentLine != null) {
String splitLine[] = currentLine.split(","); //choose delimiter here
//process cells as needed
//write output somewhere so other program can read it later
currentLine = reader.readLine();
}
}
catch (IOException ex) {
System.out.println(ex.getMessage()); //maybe write to an error log
System.exit(1);
}
"input" data to other app::you can use pipes if you're at the command line. but I'd recommend you write to a file and have the other app read it. here's an expansion of the previous code snippet showing how to write to a file as that might be more practical and easier to log/archive/debug.
try (BufferedReader reader = new BufferedReader(new FileReader(new File("user_input.csv")));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("process_me.csv")))) {
String currentLine = reader.readLine();
while (currentLine != null) {
String splitLine[] = currentLine.split(","); //choose delimiter here
//process cells as needed
writer.write(processed_stuff);
currentLine = reader.readLine();
}
}
catch (IOException ex) {
System.err.println(ex.getMessage());
System.exit(1);
}
Then retrieving output::can just be reading another file with another Java program. This way you're communicating between programs using the file system. You must agree upon file formats and directories though. And you'll be limited to having both programs on the same server.
To make this at scale, you could use web services assuming the other program you're making requests to is a web service or has one wrapped around it. You can send your file and receive some response using URLConnection. This is where things will get much more complex, but now everything in your new program is just one Java program and the other code can live on another server.
Building the app first with those "intermediate" files between the user input code, the external code, and the final code will help you focus on perfecting the business logic, then you can worry about just communication over the network.

Java / Android: Read and parse .txt file from a url

Using java in android studio I am trying to read a .txt file and parse it to obtain some data.
the file: https://www.ndbc.noaa.gov/data/latest_obs/latest_obs.txt
I am using he following code to parse the data:
String[] splited = str.trim().replaceAll(" +", " ").split(" ");
String sDate1= splited[3] + "/" + splited[4] + "/" + splited[5]
+ "/" + splited[6] + "/" + splited[7];
try{
java.util.Date date1 = new
java.text.SimpleDateFormat("yyyy/MM/dd/hh/mm").parse(sDate1);
System.out.println(date1);
}
catch(Exception e){
System.out.println(e.getMessage());
}
String windSpeed = splited[9];
String waveHeight = splited[11];
String airTemperature = splited[17];
String waterTemperature = splited[18];
System.out.println(windSpeed);
System.out.println(waveHeight);
System.out.println(airTemperature);
System.out.println(waterTemperature);
if(windSpeed.toLowerCase().equals("mm")){
// write your code here
}
if(waveHeight.toLowerCase().equals("mm")){
// write your code here
}
if(airTemperature.toLowerCase().equals("mm")){
// write your code here
}
if(waterTemperature.toLowerCase().equals("mm")){
// write your code here
}
The '//write your code here' will just return 'data N/A' since mm refers to missing data.
My problem is I am unsure how to open the file from the url to be read. I would like to open the file every hour, and parse the data below so i can assign it to their buoys in my application.
Your data file is coming from the Internet, so you'll need to download the file first before parsing it. While it is possible to download and parse the file at the same time, let's keep it simple at first.
To download the file, there are many ways to do this, but you might start with OkHttp or UrlConnection (see this SO answer for more info). If you want an alternative, check out Retrofit. Retrofit is a wrapper around OkHTTP to make it a little easier to use for experienced developers, but if you're just getting started, I'd recommend sticking with OkHttp for now until you understand what's going on.
Once the file is downloaded or in memory, you'll probably want to use BufferedReader (as suggested by rileyjsumner) to read and parse one line at a time using the code you posted.
Because you're asking specifically about Android, you'll need to keep a few things in mind:
When reading and writing temporary files, you'll want to use the temporary storage. Check out this documentation for more details: https://developer.android.com/training/data-storage/files
you'll need to do the downloading and file I/O on a separate thread. Android is inherently multithreaded and relies on the main thread to only update the UI. Everything else should be done on a different thread. There are several ways to do this. (see this post or the documentation). Once you get more comfortable with this, you might move on to RxJava.
You may want to use BufferedReader - javadoc
BufferedReader reader = new BufferedReader(new FileReader("url.txt"));
You can then scan through the context of the file.
while(line = reader.readLine() != null) {
// some code
}
This answer has more information on BufferedReader's as well

Storing a file as part of android manifest for deployment and then opening it?

Okay I know this should be dead simple but I guess I'm not phrasing my question correctly in my Google & stackoverflow searches.
I have a substantial amount of static data (6 megs) I need to load into my database upon install. Right now I'm fetching a json data file from my web server on first run and populating my database but that can be slow and something could go wrong. I'd prefer to just include the data file in the manifest and then load it on install or first run.
So, where do I put the file, make it so that it ends up on the target device, and then open it?
I've tried putting it in /res/files/ and then doing:
InputStream inputStream = new FileInputStream("/res/files/foo.json");
but of course I'd have been shocked if that had worked.
While I'm at it I should probably use CSV format instead as that would cut down the size but that's another story, I don't seem to have a way to parse it but I do know how to parse JSON data. Sorry I'm a bit new at this. Thanks!
You could store it either in assets or in res\raw.
How to open it from the assets folder:
InputStream is = getAssets().open("foo.json");
How to open it from the res\raw folder:
getResources().openRawResource(R.raw.foo);
I would advise you to use SQLite and/or XML. What #Gabriel suggested will most likely work fine, but loading and processing 6MBs may take some time -a time window of 1 to 5 secs to my experience. Since you downloaded from your webserver I believe your data has some form of structure and in your app you won't need all of the data at once.
Here are some guides/tutorials about SQLite in android, keep in mind that XML is also viable and some will probably advocate XML over SQLite in this case.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
http://www.vogella.com/tutorials/AndroidSQLite/article.html
You can put your JSON file in the raw folder (res/raw) and load it with this code :
InputStream inputStream = getResources().openRawResource(R.raw.foo);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
JSONArray jArray = new JSONArray(sb.toString());
Then you can use your knowledge to parse the JSONArray.

Iterate through a log file in Java. Pull files scanned

I currently have a log file(see bellow) that I need to iterate through and pull out a list of files that were scanned. Then by using that list of files copy the scanned files into a different directory.
So in this case, it would go through and pull
c:\tools\baregrep.exe
c:\tools\baretail.exe
etc etc
and then move them to a folder, say c:\folder\SafeFolder with the same file structure
I wish I had a sample of what the output was on a failed scan, but this will get me a good head start and I can probably figure the rest out
Symantec Image of Log File
Thanks in advanced, I really appreciate any help that you can lend me.
This question is tagged as Java, and as much as I love Java, this problem is something that would be easier and quicker to solve in a language such as Perl (so if you only want the end result and do not need to run in a particular environment then you may wish to use a scripting language instead).
Not a working implementation, but code along the lines of the below is all it would take in perl: (Syntax untested and likely broken as is, only serves as a guideline.. been awhile since I wrote any perl).
use File::Copy;
my $outdir = "c:/out/";
while(<>)
{
my ($path) = /Processing File\s+\'([^\']+)\'/;
my ($file) = $path =~ /(.*\\)+([^\\]+)/;
if (($file) && (-e $path))
{
copy($path,$outdir . $file);
}
}
This should do the trick. Now, just adapt for your solution!
public static void find(String logPath, String safeFolder) throws FileNotFoundException, IOException {
ArrayList<File> files = new ArrayList<File>();
BufferedReader br = new BufferedReader(new FileReader(logPath));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
Pattern pattern = Pattern.compile("'[a-zA-Z]:\\\\.+?'");
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
}
if (matcher.find()) {
files.add(new File(matcher.group()));
System.out.println("Got a new file! " + files.get(files.size() - 1));
}
}
for (File f : files) {
// Make sure we get a file indeed
if (f.exists()) {
if (!f.renameTo(new File(safeFolder, f.getName()))) {
System.err.println("Unable to move file! " + f);
}
} else {
System.out.println("I got a wrong file! " + f);
}
}
}
Its straight forward.
Read the Log file line by line using NEW_LINE as your deliminator. If this is a small file, feel free to load it & process it via String.split("\n") or StringTokenizer
As you loop each line, you need to do a simple test to detect if that string contains 'Processing File '.
If it does, using Regular Expression (harder) or simple parsing to capture the file names. It should be within the ['], so detect the first occurrence of ['], and detect the second, and get the string in between.
If your string is valid (you may test using java.io.File) or existing, you could copy the file name to another file. I would not advise you against copying it in java for memory restrictions for starters.
Instead, copy the string of files to form a batch file to copy them at once using the OS Script like Windows BAT or Bash Script, eg cp 'filename_from' 'copy_to_dir'
Let me know of you need a working example
regards

Opening and Analyzing ASCII files

How do I open and read an ASCII file? I'm working on opening and retrieving contents of the file and analying it with graphs.
Textbased files should be opened with a java.io.Reader. Easiest way would be using a BufferedReader to read it line by line in a loop.
Here's a kickoff example:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/path/to/file.txt"));
for (String line; (line = reader.readLine()) != null;) {
// Do your thing with the line. This example is just printing it.
System.out.println(line);
}
} finally {
// Always close resources in finally!
if (reader != null) try { reader.close(); } catch (IOException ignore) {}
}
To breakdown the file content further in tokens, you may find a Scanner more useful.
See also:
Java IO tutorial
Scanner tutorial
Just open the file via the java.io methods. Show us what you've tried first, eh?
Using Guava, you could:
String s = Files.toString(new File("/path/to/file"), Charsets.US_ASCII));
More information in the javadoc.
It's probably enormous overkill to include the library for this one thing. However there are lots of useful other things in there. This approach also has the downside that it reads the entire file into memory at once, which might be unpalatable depending on the size of your file. There are alternative APIs in guava you can use for streaming lines too in a slightly more convenient way than directly using the java.io readers.

Categories