We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › load strings that are not utf-8
Page Index Toggle Pages: 1
load strings that are not utf-8 (Read 588 times)
load strings that are not utf-8
Jul 23rd, 2009, 6:59am
 
Hello

I'm in troble with loading text files that are not in utf-8 encoding.
They contain special characters that do not display correctly in Processing.
Is there a way I can tell Processing to load a text file in a specified encoding?
Or is there a way to convert the encoding after I loaded the file?

I tried it with the getBytes("iso-8859-2") java function but didn't get it to work.

Thanks for your help,

broenni
Re: load strings that are not utf-8
Reply #1 - Jul 23rd, 2009, 8:01am
 
The trick is to use the createInput() method, so that you can still open files from the data folder, but have a lot more control.

Code:

String fileName = "isofile.txt";

void setup() {
 try {

   /* Open a stream to a File (in your data Folder) here */
   InputStream fi = createInput(fileName);
           
   /* get a reader with your encoding */
   InputStreamReader input = new InputStreamReader(fi, "iso-8859-2");
   BufferedReader reader = new BufferedReader(input);
   
   // read the file line by line
   String line;
   while ((line = reader.readLine()) != null) {
     println(line);
   }
   reader.close();

 } catch (IOException e) {
   e.printStackTrace();
 }
       
}



(OK closing the reader there is not totally failsafe, but hey it's a sketch)
Re: load strings that are not utf-8
Reply #2 - Aug 6th, 2009, 4:06am
 
Yes this seems to work fine.
I modified it slightly so I have the exact same result as from loadStrings()

thanks.

Code:

String[] lines = new String[0];

void setup() {
}
void draw() {
}

void keyPressed() {
 lines = new String[0];
 
 String filename = "myFile.CSV";
 File f = new File(dataPath(filename));
 
 if(f.exists()) {
   //lines = loadStrings(filename);

   try {
     /* Open a stream to a File (in your data Folder) here */
     InputStream fi = createInput(filename);  
     /* get a reader with your encoding */
     InputStreamReader input = new InputStreamReader(fi, "iso-8859-1");
     BufferedReader reader = new BufferedReader(input);

     // read the file line by line
     String line;
     int counter = 0;
     while ((line = reader.readLine()) != null) {
       lines = append(lines, line);
       counter++;
     }
     reader.close();
   }
   catch (IOException e) {
     e.printStackTrace();
   }
 }
}
Page Index Toggle Pages: 1