This question already has answers here:
Find location of a removable SD card
(24 answers)
Closed 4 years ago.
I need SdCard path to save files in it. I have tried some codes but these code didn't work on some devices or Android versions. Now I need a code/path that get SdCard path for all device and all Android versions.
For getting sdcard path,try following code:
public static String getExternalSDCardRootDirectory() {
String cmdMOUNT = "cat /proc/mounts";
Runtime run = Runtime.getRuntime();
List<String> paths = new ArrayList<>();
try {
Process p = run.exec(cmdMOUNT);
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
String lineStr;
while ((lineStr = inBr.readLine()) != null) {
Log.d(TAG, lineStr);
if (lineStr.toLowerCase().contains("sdcard") || lineStr.toLowerCase().contains("ext") ) {
String[] strArray = lineStr.split(" ");
if (strArray.length >= 3 &&
(!strArray[1].contains("/system") &&
!strArray[1].contains("/data") &&
!strArray[1].contains("/cache") &&
!strArray[1].contains("/persist")
)) {
String result = strArray[1].trim();
if((result.contains("ext") || result.contains("1")) && result.contains("storage")) {
paths.add(result);
}
//return result;
}
}
if (p.waitFor() != 0 && p.exitValue() == 1) {
Log.e(TAG, "check mount info failed");
return null;
}
}
inBr.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (paths.size() > 0) {
return paths.get(0);
}
else {
return null;
}
}
For getting path you need to call Environment.getExternalStorageState()
I've found an existing post.
Simply change it to...
public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
The tested solution on different platforms can be found here.
Related
So I'm trying to use a BufferedReader to split a text file into 2 different arrays, I've written some code but I'm not sure where to go from here.
I know how to populate an array, but i just cant seem to get the specific lines.
So, one array for NEW_OFFICE containing only the numbers, and one for MAIN_ADDRESS containing only the numbers below it.
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("myDelivery.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String words = read.split("NEW_OFFICE")[0];
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception ignored) { }
}
This is the text file:
NEW_OFFICE
-92.48392883 52.96531732
-2.483984994 92.48392883
MAIN_ADDRESS
-1.207614869 52.98908196
NEW_OFFICE always is the first line, and always has two lines below
it, the same goes for MAIN_ADDRESS it always has one line below it.
NEW_OFFICE & MAIN_ADDRESS can't appear more than once.
Based on your comment mentioned above, given below is the solution:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
String[][] office = new String[2][2];
String[][] main = new String[1][2];
try (BufferedReader in = new BufferedReader(new FileReader("myDelivery.txt"))) {
String read;
while ((read = in.readLine()) != null) {
if (read.equalsIgnoreCase("NEW_OFFICE")) {
// Read next two lines
for (int i = 0; i < 2; i++) {
if ((read = in.readLine()) != null) {
office[i] = read.split("\\s+");
}
}
} else if (read.equalsIgnoreCase("MAIN_ADDRESS")) {
// Read next line
if ((read = in.readLine()) != null) {
main[0] = read.split("\\s+");
}
}
}
}
// Display office[][]
System.out.println("Displaying office:");
for (String[] officeData : office) {
System.out.println(Arrays.toString(officeData));
}
// Display main[][]
System.out.println("Displaying main:");
for (String[] mainData : main) {
System.out.println(Arrays.toString(mainData));
}
}
}
Output:
Displaying office:
[-92.48392883, 52.96531732]
[-2.483984994, 92.48392883]
Displaying main:
[-1.207614869, 52.98908196]
Notes:
\\s+ is for splitting the line on space(s).
Use try-with-resources syntax to simplify your code.
.split() does take a string, but it should be a regex, not the substring that you want to split it on. You want to change your code like this:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String read;
String office = "";
while ((read = in.readLine()) != null) {
if (read.contains("NEW_OFFICE")) {
office = "NEW_OFFICE";
} else if (read.contains("MAIN_ADDRESS")) {
office = "MAIN_ADDRESS";
} else {
System.out.println(office + " : " + read);
}
}
} catch (IOException e) {
e.printStackTrace();
}
I have also changed your try with try-with-resources so you don't have to worry about closing the resource.
I´d go with somethin like this.
Please be aware that I don´t have an IDE right now so this is basically pseudo code:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String line = null;
boolean isOffice = false;
ArrayList<double> officeInts = new ArrayList<double>();
ArrayList<double> addressInts = new ArrayList<double>();
while ((line = in.readLine()) != null) {
if (line.contains("NEW_OFFICE")) {
isOffice = true;
continue;
} else if (line.contains("MAIN_ADDRESS")) {
isOffice = false;
continue;
}
for(String s : line.split(" "){
double num = Double.parseDouble(s);
if(isOffice) {
officeInts.add(num);
} else {
addressInts.add(num);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
I am migrating a webapp from Java 8 to 11 (and Tomcat 8 to 9) and i have a Client that downloads ZIP Archive Files from a Service using the following methods:
public HTTPResponse doGet(String aUrl, HashMap<String,String> aRequestParams, HashMap<String,String> aRequestProperties)
throws Exception
{
try
{
String lUrl = aUrl;
if (aRequestParams != null && aRequestParams.size() > 0)
{
StringBuffer lBodyStringBuffer = new StringBuffer();
for(String lParam : aRequestParams.keySet())
{
String lValue = aRequestParams.get(lParam);
if(lValue != null && !"".equals(lValue.trim()))
{
if(lBodyStringBuffer.length() > 0)
{
lBodyStringBuffer.append("&");
}
lBodyStringBuffer.append(URLEncoder.encode(lParam, sDEFAULTENCODING)).append("=").append(URLEncoder.encode(lValue, sDEFAULTENCODING));
}
}
String lParamString = lBodyStringBuffer.toString();
if (lParamString != null && lParamString.length() > 0)
{
if (!(lUrl.endsWith(sURLPARAMSLEADER) || aUrl.endsWith(sURLPARAMSSEPARATOR)))
{
if (lUrl.indexOf(sURLPARAMSLEADER) > -1)
{
lUrl = lUrl + sURLPARAMSSEPARATOR;
}
else
{
lUrl = lUrl + sURLPARAMSLEADER;
}
}
lUrl = lUrl + lParamString;
}
}
HttpURLConnection lConnection = createConnection(lUrl,sREQUESTETHOD_GET,null, aRequestProperties);
HTTPResponse lReturn = getResponseFromConnection(lConnection);
return lReturn;
}
catch(Exception lException)
{
throw new Exception("Fehler beim Durchführen der Anfrage: " + lException.getMessage(), lException);
}
}
private HTTPResponse getResponseFromConnection(HttpURLConnection aConnection)
throws Exception
{
InputStream lConnectionInputStream = null;
ByteArrayOutputStream lResponseByteArrayOutputStream = null;
try
{
aConnection.setRequestProperty("Accept", "application/zip");
int lStatusCode = aConnection.getResponseCode();
String lResponseCharset = getCharsetFromResponseContentType(aConnection.getContentType());
if (lResponseCharset == null)
{
if (lResponseCharset == null ||lResponseCharset.trim().length() == 0)
{
lResponseCharset = "UTF-8";
}
}
if (HttpURLConnection.HTTP_OK == lStatusCode)
{
lConnectionInputStream = aConnection.getInputStream();
}
else
{
lConnectionInputStream = aConnection.getErrorStream();
}
String lMessage = "";
if (lConnectionInputStream != null)
{
lResponseByteArrayOutputStream = new ByteArrayOutputStream();
int lBufferSize = 4096;
byte[] lBuffer = new byte[lBufferSize];
int lLength = 0;
while ((lLength = lConnectionInputStream.read(lBuffer, 0, lBufferSize)) != -1)
{
lResponseByteArrayOutputStream.write(lBuffer, 0, lLength);
}
byte[] lResponseByte = lResponseByteArrayOutputStream.toByteArray();
lMessage = new String (lResponseByte,lResponseCharset);
}
HTTPResponse lReturn = new HTTPResponse(lStatusCode, lMessage);
return lReturn;
}
catch(Exception lException)
{
throw lException;
}
finally
{
if (lResponseByteArrayOutputStream != null)
{
try{lResponseByteArrayOutputStream.close();}catch(Exception e){}
}
if (lConnectionInputStream != null)
{
try{lConnectionInputStream.close();}catch(Exception e){}
}
}
}
This is how i actually call the service via HTTP Get and save the data:
HTTPResponse lResponse = new HTTPRequest().doGet("http://localService.com/, null, null);
FileOutputStream lFileOutputStream = new FileOutputStream("exampleFile.zip", false);
lFileOutputStream.write(lResponse.getMessage().getBytes());
lFileOutputStream.close();
So this used to Work before and i am getting a headache about what might have changed. When i download the ZIP File with url in my Browser, everything seems fine, so the Service seems to work. But with my client the ZIP Files get corrupted and cannot be opened. The are not empty but they differ in size: surprisingly the corrupted files are about 50% larger than the ones downloaded via browser.
Does anyone know what the problem here is?
Ok,the problem was the return type String of the method getResponseFromConnection. I changed it and now write the file directly with the File.copy() method which VGR suggested.
I have got two text files with data in the following format
data.txt file as following format
A 10
B 20
C 15
data1.txt file is in format (start node,end node, distance):
A B 5
A C 10
B C 20
I am trying to implement a search strategy, for that I need to load the data from data.txt and ONLY the start node and end node from data1.txt (i.e. I dont need the distance). I need to store this information in a stack as I think it would be a best data structure for implementing greedy search.
Actually I am not sure how to get started with file I/O to read these files and store them in array to implement greedy search. So I would highly appreciate any starting idea on how to proceed.
I am new to this, so please bear with me. Any help is much appreciated. Thanks.
EDIT:
Here is what I have got till now
String heuristic_file = "data.txt";
try
{
FileReader inputHeuristic = new FileReader(heuristic_file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
while ((line = bufferReader.readLine()) != null)
{
System.out.println(line);
}
bufferReader.close();
} catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
My approach, doesn't differ fundamentally from the others. Please regard the try/catch/finally blocks. Always put the closing statements into the finally block, so the opened file is guaranteed to be closed, even if an exception was thrown while reading the file.
The part between the two //[...] could surely be done more efficient. Maybe reading the whole file in one take and then parsing the text backwards and searching for a line-break? Maybe a Stream-API supports to set the reading position. I honestly don't know. I didn't need that, up to now.
I chose to use the verbose initialization of the BufferedReader, because then you can specify the expected encoding of the file. In your case it doesn't matter, since your files do not contain symbols out of the standard ASCII range, but I believe it's a semi-best-practice.
Before you ask: r.close() takes care of closing the underlying InputStreamReader and FileInputStream in the right order, till all readers and streams are closed.
public static void readDataFile(String dir, String file1, String file2)
throws IOException
{
File datafile1 = new File(dir, file1);
File datafile2 = new File(dir, file2);
if (datafile1.exists())
{
BufferedReader r = null;
try
{
r = new BufferedReader(
new InputStreamReader(
new FileInputStream(datafile1),
"UTF-8"
)
);
String row;
Stack<Object[]> s = new Stack<Object[]>();
String[] pair;
Integer datapoint;
while((row = r.readLine()) != null)
{
if (row != null && row.trim().length() > 0)
{
// You could use " " instead of "\\s"
// but the latter regular expression
// shorthand-character-class will
// split the row on tab-symbols, too
pair = row.split("\\s");
if (pair != null && pair.length == 2)
{
datapoint = null;
try
{
datapoint = Integer.parseInt(pair[1], 10);
}
catch(NumberFormatException f) { }
// Later you can validate datapairs
// by using
// if (s.pop()[1] != null)
s.add(new Object[] { pair[0], datapoint});
}
}
}
}
catch (UnsupportedEncodingException e1) { }
catch (FileNotFoundException e2) { }
catch (IOException e3) { }
finally
{
if (r != null) r.close();
}
}
// Do something similar with datafile2
if (datafile2.exists())
{
// [...do the same as in the first try/catch block...]
String firstrow = null, lastrow = null;
String row = null;
int i = 0;
do
{
lastrow = row;
row = r.readLine();
if (i == 0)
firstrow = row;
i++;
} while(row != null);
// [...parse firstrow and lastrow into a datastructure...]
}
}
use split
while ((line = bufferReader.readLine()) != null)
{
String[] tokens = line.split(" ");
System.out.println(line + " -> [" + tokens[0] + "]" + "[" + tokens[1] + "][" + tokens[2] + "]");
}
if you must have this in an array you can use the following:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
public class NodeTest {
public static void main(String[] args) throws ParseException {
try {
File first = new File("data.txt");
File second = new File("data1.txt");
Node[] nodes1 = getNodes(first);
Node[] nodes2 = getNodes(second);
print(nodes1);
print(nodes2);
}
catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
}
public static final void print(Node[] nodes) {
System.out.println("======================");
for(Node node : nodes) {
System.out.println(node);
}
System.out.println("======================");
}
public static final Node[] getNodes(File file) throws IOException {
FileReader inputHeuristic = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
List<Node> list = new ArrayList<Node>();
while ((line = bufferReader.readLine()) != null) {
String[] tokens = line.split(" ");
list.add(new Node(tokens[0], tokens[1]));
}
bufferReader.close();
return list.toArray(new Node[list.size()]);
}
}
class Node {
String start;
String end;
public Node(String start, String end){
this.start = start;
this.end = end;
}
public String toString() {
return "[" + start + "][" + end + "]";
}
}
Something like this?
HashSet<String> nodes = new HashSet<String>();
try(BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
nodes.add(l[0]);
line = br.readLine();
}
}
try(BufferedReader br = new BufferedReader(new FileReader("data1.txt"))) {
String line = br.readLine();
while (line != null) {
String[] l = line.split(" ");
if (nodes.contains(l[0]) || nodes.contains(l[1]))
// Do whatever you want ...
line = br.readLine();
}
}
I want to save to a file in android , Some of my arrayList that will be deleted after that.I already have two methods to write/read from android file here but the problem is I want the two methods do that:
the first method must save the element of arraylist then if I call it again it will not write the new element in the same line but write it in another line
The second must read a line (for example I give to the method which line and it returns what the lines contains)
The file looks like that :
firstelem
secondelem
thridelem
anotherelem
another ..
is this possible to do in android java?
PS: I don't need database.
Update
This is My methods :
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
// stringBuilder.append("\\n");
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Using the save method you linked to you can create the text to save with a StringBuilder:
public String makeArrayListFlatfileString(List<List<String>> listOfLists)
{
StringBuilder sb = new StringBuilder();
if (!listOfLists.isEmpty()) {
// this assumes all lists are the same length
int listLengths = listOfLists.get(0).size();
for (int i=0; i<listLengths; i++)
{
for (List<String> list : listOfLists)
{
sb.append(list.get(i)).append("\n");
}
sb.append("\n"); // blank line after column grouping
}
}
return sb.toString();
}
To parse the contents from that same file (again assuming equal length lists and a String input):
public List<List<String>> getListOfListsFromFlatfile(String data)
{
// split into lines
String[] lines = data.split("\\n");
// first find out how many Lists we'll need
int numberOfLists = 0;
for (String line : lines){
if (line.trim().equals(""))
{
// blank line means new column grouping so stop counting
break;
}
else
{
numberOfLists++;
}
}
// make enough empty lists to hold the info:
List<List<String>> listOfLists = new ArrayList<List<String>>();
for (int i=0; i<numberOfLists; i++)
{
listOfLists.add(new ArrayList<String>());
}
// keep track of which list we should be adding to, and populate the lists
int listTracker = 0;
for (String line : lines)
{
if (line.trim().equals(""))
{
// new block so add next item to the first list again
listTracker = 0;
continue;
}
else
{
listOfLists.get(listTracker).add(line);
listTracker++;
}
}
return listOfLists;
}
For writing, just as Illegal Argument states - append '\n':
void writeToFileWithNewLine(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data + "\n");
outputStreamWriter.close();
}
catch (IOException e) { /* handle exception */ }
}
For reading (just the idea, in practice you should read the file only once):
String readLine(final int lineNo) {
InputStream in = new FileInputStream("file.txt");
ArrayList<String> lines = new ArrayList<String>();
try {
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inReader);
String line;
do {
line = reader.readLine();
lines.add(line);
} while(line != null);
} catch (Exception e) { /* handle exceptions */ }
finally {
in.close();
}
if(lineNo < lines.size() && lineNo >= 0) {
return lines.get(lineNo);
} else {
throw new IndexOutOfBoundsException();
}
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
When i tried to run this program, it only show "Beginning of Read-in records list. But the program doesnt terminate, which means the program keep running, but it doesnt output anything. Could anyone please help?
public static void readFile(String fileName, PhoneBook book_list)
{
if(fileName == null) return;
File file = new File(fileName);
if(!file.isFile())
{
System.out.println("File not found!");
return ;
}
Person person = new Person();
boolean invalid = false;
System.out.println("\nInfo: Beginning of Read-in records list.\n");
try
{
BufferedReader input = new BufferedReader(new FileReader(file));
try
{
String line = "";
line = input.readLine();
while(line != null)
{
line = line.trim();
String[] words = line.split("\\s+");
if(invalid)
{
if(words[0].equals(""))
{
person = new Person();
invalid = false;
}
}
//refer to end of a record
else if(words[0].equals(""))
{
if(person.validation())
{
book_list.addPerson(person);
person = new Person();
}
else
{
person = new Person();
}
}
if(words[0].equalsIgnoreCase("name"))
{
if(words.length<2)
{
invalid=true;
}
else
{
String name = words[1];
for(int i=2; i<words.length;i++)
{
name = name + " " + words[i];
}
for(int i=0; i<name.length(); i++)
{
if((name.codePointAt(i) >= 97 && name.codePointAt(i) <= 122)/*a-z*/
|| (name.codePointAt(i) >= 65 && name.codePointAt(i) <= 90)/*A-z*/
|| name.codePointAt(i) == 32)/*space*/
{continue;}
else
{
invalid=true;
break;
}
}
if(!invalid)
{
person.setName(name);
}
}
}
else if(words[0].equalsIgnoreCase("birthday"))
{
if(words.length !=2)
{
invalid=true;
}
else
{
try
{
person.setBirthday(words[1]);
book_list.addPerson(person);
}
catch (ParseException e)
{
invalid = true;
}
}
}
else if(words[0].equalsIgnoreCase("phone"))
{
if(words.length != 2)
{
invalid = true;
}
else
{
String phone = Tools.parsePhone(words[1]);
if(phone!=null)
{
person.setPhone(phone);
}
else
{
invalid = true;
}
}
}
else if(words[0].equalsIgnoreCase("email"))
{
if(words.length != 2)
{
invalid = true;
}
else
{
if(Tools.validateEmail(words[1]))
{
person.setEmail(words[1]);
}
else
{
invalid = true;
}
}
}
else if(words[0].equalsIgnoreCase("address"))
{
String address = line.substring(words[0].length()).trim();
String addr="";
do
{
line = input.readLine();
if(line == null)
{
person.setAddress(address);
}
if(!invalid && person.validation())
{
book_list.addPerson(person);
}
addr = line.trim();
String[] adds = addr.split("\\s+");
if(!adds[0].equals("")
&& !adds[0].equalsIgnoreCase("name")
&& !adds[0].equalsIgnoreCase("birthday")
&& !adds[0].equalsIgnoreCase("phone")
&& !adds[0].equalsIgnoreCase("email")
&& !adds[0].equalsIgnoreCase("address"))
{
address = address + " " + addr;
}
else break;
}
while(true);
if(line == null)
break;
}
}// end of while loop
}
finally
{
input.close();
}
}
catch(IOException ex)
{
System.err.print("Error: Open records file failed");
return;
}
System.out.println("\nInfo: End of Read-in records list.\n");
return;
}
public static void main(String[] args)
{
String personFile = null; // person contact information file
String instFile = null; //instruction file
String outputFile = null; //output file name;
String reportFile = null; //report file name;
PhoneBook book_list = new PhoneBook();
FileIO2.readFile("C:/Users/phoenix/Desktop/sample_phonebook1.txt", book_list);
ArrayList<Person> a;
a = book_list.getPersonList();
System.out.println(a.size());
}
I think your problem is here:
// initializes "line" String
String line = "";
// Tells BufferedReader to read one line (the first line)
line = input.readLine();
// loops infinitely since String read from first line is not null in this specific case
while(line != null)
{
...
Try this:
// initializes "line" String
String line = "";
// tells the BufferedReader to read a new line _until_ the new line is null
// ... if new line is null we reached EOF
while ((line = input.readLine() != null) {
...
You should do:
String line = null;
while ((line = input.readLine()) != null) {
...
...
}
Instead of:
String line = "";
line = input.readLine();
while(line != null){
...
...
}
Keep reading files. Cheers! :P
You have used while & do..while loop..
And you are not reading file properly
after do..while you should include line = input.readLine()