I want to create a new folder/directory called lists but it just keeps on failing, if anyone had any suggestions that would be greatly appreciated. Thank you.
File file = new File(this.getFilesDir() +File.separator +"Lists");
if(file.mkdirs()){
System.out.println("Directory success");
}else{
System.out.println("Directory failed!");
}
System.out.println(file.getAbsolutePath());
if(file.isDirectory()){
System.out.println("File is a directory");
File lists[] = file.listFiles();
String names[] = new String[lists.length];
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
}else{
System.out.println("File is not a directory");
}
My first answer is completely incorrect (my apologies for that)! I believe this one is correct.
I think problem lies with the following lines:
File lists[] = file.listFiles();
String names[] = new String[lists.length];
if(lists.length > 0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
You had just created the folder so there will be no files in it so lists[] won't have any size, but in your else statement you are adding an item to the names array even though it doesn't have a size. Removing names[0] = "Create New List"; from the else statement should work.
Related
public static FAQ_Alisa_QnA[] oipReadQuestion(){
String questionA1,thisUser;
int indexQuestion;
String [] entryDetails;
FAQ_Alisa_QnA [] entries = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File file = new File ("ReadOIP.txt");
int count = 0;
try{
Scanner sc = new Scanner(file);
//do this while there is a next line in file.
while(sc.hasNextLine()){
String line = sc.nextLine();
entryDetails = line.split(";");
// index = entryDetails[0];
indexQuestion = Integer.parseInt(entryDetails[0]);
thisUser = entryDetails[1];
questionA1 = entryDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexQuestion = indexQuestion;
a.thisUsername = thisUser;
a.questionA1 = questionA1;
entries [count] = a;
count++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA [] allQuestions = new FAQ_Alisa_QnA [count];
for(int i = 0; i < count; i++){
allQuestions[i] = entries[i];
}
return allQuestions;
}
public static FAQ_Alisa_QnA[] oipReadAnswers(){
String indexAnswer, answer11, thisUser;
String [] answerDetails;
FAQ_Alisa_QnA [] answers = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File thisFile = new File ("AnsReadOIP.txt");
int count1 = 0;
try{
Scanner sc1 = new Scanner(thisFile);
//do this while there is a next line in file.
while(sc1.hasNextLine()){
String line = sc1.nextLine();
answerDetails = line.split(";");
// index = entryDetails[0];
indexAnswer = answerDetails[0];
thisUser = answerDetails[1];
answer11 = answerDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexAnswer = Integer.parseInt(indexAnswer);
a.thisUsername = thisUser;
a.answer11 = answer11;
answers [count1] = a;
count1++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA[] allAnswers = new FAQ_Alisa_QnA[count1];
for(int i = 0; i < count1; i++){
allAnswers[i] = answers[i];
}
return allAnswers;
}
public static void oipPrintQnA(){
FAQ_Alisa_QnA [] allQuestions = oipReadQuestion();
FAQ_Alisa_QnA [] allAnswers = oipReadAnswers();
System.out.println("Organization in project work");
System.out.println("=============================");
for(int i = 0; i < allQuestions.length; i++){
System.out.println( allQuestions[i].indexQuestion + "-" + "Question" + ":");
System.out.println(allQuestions[i].thisUsername + ":" +allQuestions[i].questionA1);
System.out.println(" ");
for(int j = 0; j < allAnswers.length; j++){
if(allQuestions[i].indexQuestion == allAnswers[j].indexAnswer){
System.out.println("Answer for question "+ + allAnswers[j].indexAnswer+ ":" );
System.out.println(allAnswers[j].thisUsername+ ":" +allAnswers[j].answer11);
System.out.println(" ");
}
}
}
}
//So I have read answers and questions and I saved my qns and answers in 2 different text files. This is because I have add functions to it but i never put it here cuz my qn is not related to that. I just wanna know how to print out the qn and answer in 2 lines so that if the qn is so long then it can print out in two lines//
So these are how my text files look like:
ReadOIP.txt
1;Shafiq;How to organize your time well when you're juggling with so many project work and assignments on the same day? Best answer:The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment.
2;Rohannah;Does having a timetable works to finish your project on time?
3;lymeoww;Is task allocation really important to be organized in project work?
AnsReadOIP.txt
1;Andy23;The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment .2; Does having a timetable to do your project works? //For example this line, it will print out very long on the console//
2;Betty23;of course it does!
1;Ying Qian;just organize lorh
3;lymeoww;Yes, it is important!
//Refer to this picture//
I am trying to develop a program that searches for duplicate files using MD5 hash, it will compare two hash files for duplicate.
I am having difficulties comparing the two files, after hashing the files with MD5 hash code, I keep getting the error "Java.IO.FileNotFoundException.". Here is my code, I do not know what I am doing wrong.
////////////////////// It is a GUI Program ////////////////////////
DefaultListModel m = new DefaultListModel(); // List Model for displaying the hash codes
int rval = chooser.showOpenDialog(null); //JFileChooser for selecting files tobehashed
if(rval == JFileChooser.APPROVE_OPTION){
File f = chooser.getCurrentDirectory();
String fs = f + "";
if(!f.isDirectory()){
JOptionPane.showMessageDialog(null, "Supplied Directory does not exist");
}
//display files on the TesxtField component
File[] filenames = f.listFiles();
String fn = Arrays.toString(filenames);
String type = f.isFile() ? "File" : "Directory : ";
long len = f.length();
String all = type +" "+" " + " Length: " + len;
dis.setText(all + "\n");
dis.setText(fn + "\n" + "\n" );
//Loops through the file and check sum of the list files
for(File file : f.listFiles()){
String hash;
try {
hash = MD5.asHex(MD5.getHash(file));
////////// Here is where my problems starts, Please help //////////
for(int i = 0; i < hash.length(); i++ )
for(int j = i + 1; j < hash.length(); j++){
File[] f1 = new File[i];
File[] f2 = new File[j];
boolean check = MD5.hashesEqual(MD5.getHash(new File(Arrays.toString(f1))),MD5.getHash(new File(Arrays.toString(f2)))); //compares the byte of files
System.out.println(check);
m.addElement(hash);
task.setModel(m);
}
}catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
For reading files in Java you need an InputStream object.
Look at this Question Getting a File's MD5 Checksum in Java which seems to help you with your problem
Hi I am trying load a set of "list" into a String array, and the list are simply .txt documents and I want to use the names of the files as the list name on my display, therefore I need to get all of the files in the folder that I had created named "Lists" and then display them into an arrayadapter.
private String[] getListNames() {
//generates the file containing the list names
File file = new File(this.getFilesDir() +File.separator +"Lists");
System.out.println(file.getAbsolutePath());
File lists[] = file.listFiles();
String names[] = {};
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
line of code in question according to the stacktrace (line 108)
if(lists.length >0){
StackTrace
03-25 04:37:16.981: E/AndroidRuntime(2099): Caused by: java.lang.NullPointerException
03-25 04:37:16.981: E/AndroidRuntime(2099): at dev.shaw.MyShoppingPlanner.List_Activity.getListNames(List_Activity.java:108)
private List<String> myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( root_sd + "/Lists" ) ;
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
You need to log if files.getFileList() is really returning anything or not:
also
change this:
File lists[] = file.listFiles();
String names[] = {};
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
to
File lists[] = file.listFiles();
String names[] = {};
if(lists != null && lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
P.S: You cannot get the length if the lists array is null in the first place.!
try this one.
//use two boolean variables.
File file;
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
//check if the sdcard is enable or disable in your device
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
private String[] getListNames() {
if (mExternalStorageAvailable) {
File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
if (!path.exists()) {
path.mkdirs();
}
file=path.getAbsolutePath();
}
else {
//use ContextWrapper it a onw way to access internal storage.
ContextWrapper cw = new ContextWrapper(getApplicationContext());
(or)
//generates the file containing the list names
file = new File(this.getFilesDir() +File.separator +"Lists");
if (!file.exists()) {
file.mkdirs();
}
System.out.println(file.getAbsolutePath());
}
File lists[] = file.listFiles();
String names[] = {};
try{
if (lists.length==0)
{
System.out.print("There is no files in the Directory");
}
else{
if(lists.length >0){
for(int i = 0; i < lists.length; i ++){
names[i] = lists[i].getName();
}
}else{
names[0] = "Create New List";
}
catch(Exception e)
{
e.printStackTrace();
}
}
I'm trying to list all files in /data/dalvik-cache folder but i keep getting NullPointerException
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
File folder = new File(dir);
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName() );
}
}
The array dalvikPath contains /data/dalvik-cache
I request su before trying to list and I think i have all the permissions in my manifest.
I think you need to check directory is exist or not . then you can get list of files
File folder = new File(dir);
if(folder.exists()){
File list[] = folder.listFiles();
if(list.length>0{
for( int i=0; i< list.length; i++){
}
}
}else{
}
Ok so i've modified my code and now i don't have javanullpointer but i don't "find" an files in the folders...
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
log.append("Reading " + dir + "\n");
File folder = new File(dir);
if (folder.exists() && folder.isDirectory()){
try{
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName().toString() );
log.append(list[i].getName().toString() +"\n");
}
}
catch ( Exception e) {
}
}
else {
log.append("Folder " + dir + "doesn't exist.\n");
}
I have such code...
File fileDir = new File("/mnt/sdcard/dd");
if(!fileDir.exists() || !fileDir.isDirectory()){
return;
}
String[] files = fileDir.list();
So, I have an array of files' names...
But I want to GET an array of "path to each file"+fileDir.list()
For example
I have - "/09.jpg"
I want - "/mnt/sdcard/dd/09.jpg"
How can I do it? Thanks
try following code,
String path = "/mnt/sdcard/dd";
File fileDir = new File( path );
if(!fileDir.exists() || !fileDir.isDirectory())
{
return;
}
String[] files = fileDir.list();
for ( int i = 0 ; i < files.length ; i++ )
{
files[i] = path + "/" + files[i];
}
Now the array files contains the updated value with path.
File fileDir = new File("/mnt/sdcard/dd");
if(!fileDir.exists() || !fileDir.isDirectory()){
return;
}
File[] files = fileDir.listFiles();
for(File f: files){
Log.i("", f.getAbsolutePath());
}
What you need is getAbsolutePath(),
File file = new File("/mnt/sdcard/dd");
Files[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
Log.e("Root Path of file:" + i, files[i].getAbsolutePath());
}