Aide java file

cs_amel2006 Messages postés 83 Date d'inscription samedi 21 janvier 2006 Statut Membre Dernière intervention 9 décembre 2006 - 12 avril 2006 à 22:01
Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 - 13 avril 2006 à 00:21
je lit un fichier et je le met dans un string et mon problème est que mon string ne contient pa le debut de fichier et je ne sais pas pourquoi voici mon code:


Code:
,
----

public static void main (String [] argv) throws IOException
{
String g= fichtostr("f1.txt");
}
public static String fichtostr(String nomf)
{
char tout[] = {'r'};
try {
File sourceF = new File(nomf);
long grandComment = sourceF.length();
tout = new char[(int)grandComment];
FileReader f = new FileReader(sourceF);
int dejaLu = 0;
while (dejaLu < grandComment) {
dejaLu = dejaLu + f.read(tout, dejaLu, (int)grandComment-dejaLu);
}
}
catch (IOException e) {
System.err.println(" Cela ne marche pas. Voila." + e.toString());
}
return new String(tout);

}

merci de votre aide

amel2006

1 réponse

Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 111
13 avril 2006 à 00:21
Salut,



Si tu veux lire tout ton fichier et renvoyer le contenu dans une chaine tu peux faire :



public static void main (String [] args){

System.out.println(fileToString("f1.txt"));

}





public static String fileToString(String fileName){

File f = new File(fileName);

String data = "";

if(!f.exists()){

System.err.println("FATAL : File not found");

return null;

}

try{

BufferedReader reader = new BufferedReader(new FileReader(f));

if(!reader.ready()){

System.err.println("FATAL : Nothing to read");

return null;

}

boolean eof=false;

while(!eof){

String str = reader.readLine();

if (str == null) eof=true;

else data += str;

}

reader.close();

return data;

}catch(Exception e){

System.err.println("FATAL ERROR :");

e.printStackTrace();

return null;

}

}


WORA
0
Rejoignez-nous