I want to read and write some data from text ( .txt ) files in my android project. ( The files are going to be included in the project itself for storing some user preference data )
I want to use only PURE JAVA PROVIDED METHODS to do that, like -
Scanner myScanner = new Scanner( new File( "file_name.txt" ) );.
These are a few static data in a non-activity class. So i don't have any Context to use for calling getResources() or using SharedPreferences. And there is no way i can pass a context from elsewhere to the class. I'm not going to explain why cause it's going to be a long story. Please don't give any suggestions regarding these ways.
My question is simple - if I want to read/write files with java methods, exactly where do i need to put them in my project?
I AM USING ANDROID STUDIO.
I start with reading a simple text.txt, you first have to upload a file in an asset folder after that you create a Private String method
private String readFileFromAssets(String filename) {
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(
getAssets().open(filename)));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
return builder.toString();
} catch (FileNotFoundException e) {
displayMessage("File not found: " + e.getMessage());
} catch (Exception e) {
displayMessage(e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
displayMessage(e.getMessage());
}
}
}
return null;
}
give me a feedback about it.
Related
I have a simple game in which I would need to store a highscore (float) to a file and then read it next time the user goes on the app. I want it to be saved on the device, however, I have found no way to do that. How can I persist data on the device to a chosen location ?
You can use internal storage. This will create files that can be written to and read from. The best way to do this is to create a separate class that handles files. Here are two methods that will read and write the highscore.
To set the highscore, use setHighScore(float f).
public void setHighScore(float highscore){
FileOutputStream outputStream = null;
try {
outputStream = (this).openFileOutput("highscore", Context.MODE_PRIVATE);
outputStream.write(Float.toString(f)).getBytes());
outputStream.close();
} catch (Exception e) {e.printStackTrace();}
}
To get the highscore, use getHighScore().
public float getHighScore(){
ArrayList<String> text = new ArrayList<String>();
FileInputStream inputStream;
try {
inputStream = (this).openFileInput("highscore");
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr);
String line;
while ((line = bufferedReader.readLine()) != null) {
text.add(line);
}
bufferedReader.close();
} catch (Exception e) { e.printStackTrace();}
return Float.parseFloat(text.get(1));
}
Using File Handling -
I would suggest going basic by using a file handling technique. Auto create a text file using the java's InputStream and OutputStream classes. Then add the float inside it. As suggested in the comments above too.
Using properties files -
Refer this code - http://www.mkyong.com/java/java-properties-file-examples/
Using a database -
You can go ahead and use a database which will safely store the score and make sure no one tampers with it easily. Tutorial for this - http://www.tutorialspoint.com/jdbc/
Try simple with very few lines.
public void saveHighScore(File file, float highScore){
try{
Formatter out = new Formatter(file);
out.format("%f", highScore);
out.close();
}catch(IOException ioe){}
}
I am trying to replace a string from a js file which have content like this
........
minimumSupportedVersion: '1.1.0',
........
now 'm trying to replace the 1.1.0 with 1.1.1. My code is searching the text but not replacing. Can anyone help me with this. Thanks in advance.
public class replacestring {
public static void main(String[] args)throws Exception
{
try{
FileReader fr = new FileReader("G:/backup/default0/default.js");
BufferedReader br = new BufferedReader(fr);
String line;
while((line=br.readLine()) != null) {
if(line.contains("1.1.0"))
{
System.out.println("searched");
line.replace("1.1.0","1.1.1");
System.out.println("String replaced");
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
First, make sure you are assigning the result of the replace to something, otherwise it's lost, remember, String is immutable, it can't be changed...
line = line.replace("1.1.0","1.1.1");
Second, you will need to write the changes back to some file. I'd recommend that you create a temporary file, to which you can write each `line and when finished, delete the original file and rename the temporary file back into its place
Something like...
File original = new File("G:/backup/default0/default.js");
File tmp = new File("G:/backup/default0/tmpdefault.js");
boolean replace = false;
try (FileReader fr = new FileReader(original);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(tmp);
BufferedWriter bw = new BufferedWriter(fw)) {
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains("1.1.0")) {
System.out.println("searched");
line = line.replace("1.1.0", "1.1.1");
bw.write(line);
bw.newLine();
System.out.println("String replaced");
}
}
replace = true;
} catch (Exception e) {
e.printStackTrace();
}
// Doing this here because I want the files to be closed!
if (replace) {
if (original.delete()) {
if (tmp.renameTo(original)) {
System.out.println("File was updated successfully");
} else {
System.err.println("Failed to rename " + tmp + " to " + original);
}
} else {
System.err.println("Failed to delete " + original);
}
}
for example.
You may also like to take a look at The try-with-resources Statement and make sure you are managing your resources properly
If you're working with Java 7 or above, use the new File I/O API (aka NIO) as
// Get the file path
Path jsFile = Paths.get("C:\\Users\\UserName\\Desktop\\file.js");
// Read all the contents
byte[] content = Files.readAllBytes(jsFile);
// Create a buffer
StringBuilder buffer = new StringBuilder(
new String(content, StandardCharsets.UTF_8)
);
// Search for version code
int pos = buffer.indexOf("1.1.0");
if (pos != -1) {
// Replace if found
buffer.replace(pos, pos + 5, "1.1.1");
// Overwrite with new contents
Files.write(jsFile,
buffer.toString().getBytes(StandardCharsets.UTF_8),
StandardOpenOption.TRUNCATE_EXISTING);
}
I'm assuming your script file size doesn't cross into MBs; use buffered I/O classes otherwise.
I have a code which parses strings from an CSV.-file (with twitter data) and gives them to a new KML file. When i parse the comments from the twitter data there are of course unknown tokens like: 🚨. When i open up the new KML-File in Google Earth i get an error because of this unknown tokens.
Question:
When i parse the strings, can i tell java it should throw out all unknown tokens from the string so that i don't have any unknown tokens in my KML?
Thank you
Code below:
String csvFile = "twitter.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
String[] twitter = null;
int row_desired = 0;
int row_counter = 0;
String[] placemarks = new String[1165];
// ab hier einlesen der CSV
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (row_counter++ == row_desired) {
twitter = line.split(cvsSplitBy);
placemarks[row_counter] =
"<Placemark>\n"+
"<name>User ID: "+twitter[7]+"</name>\n"+
"<description>This User wrote: "+twitter[5]+" at the: "+twitter[6]+"</description>\n"+
"<Point>\n"+
"<coordinates>"+twitter[1]+","+twitter[2]+"</coordinates>\n"+
"</Point>\n"+
"</Placemark>\n";
row_desired++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
for(int i = 2; i <= 1164;i++){
String kml2 = kml.concat(""+placemarks[i]+"");
kml=kml2;
}
kml = kml.concat("</Document></kml>");
FileWriter fileWriter = new FileWriter(filepath);
fileWriter.write(kml);
fileWriter.close();
Runtime.getRuntime().exec(googlefilepath + filepath);
}
Text files are not all built equal: you must always consider what character encoding is in use. I'm not sure about Twitter's data specifically, but I would guess they're doing like the rest of the world and using UTF-8.
Basically, avoid FileReader and instead use the constructor of InputStreamReader which lets you specify the Charset.
Tip: if you're using Java 7+, try this:
for (String line : Files.readAllLines(file.toPath(), Charset.forName("UTF-8"))) { ...
More Info
The javadoc of FileReader states "The constructors of this class assume that the default character encoding"
You should avoid this class, always. Or at least for any data that might ever be transferred between computers. Even a program running on Windows "using the default charset" will assume UTF-8 when run from inside Eclipse, or ISO_8859_1 when running outside Eclipse! Such non-determinism from a class is not good.
i am using java ant to deploy my application . I have a file app.php . I want to write some text in app.php while deploying in a specific location inside that file . This is my app.php :
'providers' => array(
'Illuminate\Validation\ValidationServiceProvider',
'Illuminate\View\ViewServiceProvider',
'Illuminate\Workbench\WorkbenchServiceProvider',
),
I want to add a line at the end of this line :
'Illuminate\Workbench\WorkbenchServiceProvider',
Please tell me how to do this .
Thanks.
you must use subString method like this:
at first store your file in a String so after that you could do this:
String s="your file";
String firstPart=s.substring(0,s.lastIndexOf(")")+1);
String lastPart=s.substring(s.lastIndexOf(")")+1);
firstPart=firstPart+"\n"+"'Illuminate\\Workbench\\WorkbenchServiceProvider',";
s=firstPart+lastPart;
How to read from file ?
Use BufferedReader to wrap a FileReader
BufferedReader br = null;
StringBuilder sb=new StringBuilder();
try {
String line;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((line= br.readLine()) != null) {
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
String str=sb.toString();
See the Replace or Filter ant tasks.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
reading a specific file from sdcard in android
I'm trying to make a simple android app that basically imports a csv and inserts it to my database table. So far, I was able to read a csv file inside the res folder.
my sample csv file is named "test.csv" and is basically accessed through "InputStream is = this.getResources().openRawResource(R.drawable.test);".
Here's my sample code:
InputStream is = this.getResources().openRawResource
(R.drawable.test);
BufferedReader reader = new BufferedReader(new InputStreamReader
(is));
try {
String line;
String brand = "";
String model = "";
String type = "";
this.dh = new DataHelper(this);
//this.dh.deleteAllCar();
while ((line = reader.readLine()) != null) {
// do something with "line"
String[] RowData = line.split(",");
brand = RowData[1];
model = RowData[2];
type = RowData[3];
this.dh = new DataHelper(this);
//this.dh.deleteAllCar();
this.dh.insertcsv(brand, model, type);
}
}catch (IOException ex) {
// handle exception
}finally {
try {
is.close();
}
catch (IOException e) {
// handle exception
}
}
This works fine however, I want to be able to make a feature wherein the user can specify where to get the file(like from phone's sdcard, etc). But for now, I wanted to know how to access the csv from sdcard(mnt/sdcard/test.csv).
Help will be highly appreciated! thanks and happy coding!
Reading a file from an SDCard has been covered on Stack Overflow previously.
Here's the link:
reading a specific file from sdcard in android
Here is code on how to write to the SD Card, you should be able to figure out the read part using your code above:
private void writeToSDCard() {
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
InputStream from = myContext.getResources().openRawResource(rID);
File dir = new java.io.File (root, "pdf");
dir.mkdir();
File writeTo = new File(root, "pdf/" + attachmentName);
FileOutputStream to = new FileOutputStream(writeTo);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead); // write
to.close();
from.close();
} else {
Log.d(TAG, "Unable to access SD card.");
}
} catch (Exception e) {
Log.d(TAG, "writeToSDCard: " + e.getMessage());
}
}
}