31
Strings e I/ O Grupo de estudo para SCJP

String e IO

Embed Size (px)

Citation preview

Page 1: String e IO

Strings e I/ O

Grupo de estudo para SCJP

Page 2: String e IO

Strings e I/ O

• Tópicos abordados– String, StringBuilder, and StringBuffer

• The String Class • Important Facts About Strings and Memory• Important Methods in the String Class • The StringBuffer and StringBuilder Classes• Important Methods in the StringBuffer and

StringBuilder Classes

– File Navigation and I/ O • The java.io.Console Class

Page 3: String e IO

Strings

• Strings são objetos imutáveis• Cada caractere em uma string é 16- bit

Unicode• Como strings são objetos, é possível criar

uma instância:– ut ilizando new:

String s = new String();

String s = new String("abcdef");

– de outras maneiras:

String s = "abcdef";

Page 4: String e IO

Strings: Métodos e referências

• Métodos e referências

Page 5: String e IO

Strings: Métodos e referências

• Métodos e referências

Page 6: String e IO

Strings: Métodos e referências

• Métodos e referências

Page 7: String e IO

Strings: Métodos e referências

• Outros exemplosString x = "Java";

x.concat(" Rules!");

System.out.println("x = " + x);

x.toUpperCase();

System.out.println("x = " + x);

x.replace('a', 'X');

System.out.println("x = " + x);

– Qual será a saída?

Page 8: String e IO

Strings: Métodos e referências

• Outros exemplosString x = "Java";

x.concat(" Rules!");

System.out.println("x = " + x);

x.toUpperCase();

System.out.println("x = " + x);

x.replace('a', 'X');

System.out.println("x = " + x);

– Qual será a saída? x = Java

Page 9: String e IO

Strings: Métodos e referências

• Outro exemploString x = "Java";

x = x.concat(" Rules!");

System.out.println("x = " + x);

– E agora?

Page 10: String e IO

Strings: Métodos e referências

• Outro exemploString x = "Java";

x = x.concat(" Rules!");

System.out.println("x = " + x);

– E agora? x = Java Rules!

Page 11: String e IO

Strings: Métodos e referências

• Possível exemplo do testeString s1 = "spring ";

String s2 = s1 + "summer ";

s1.concat("fall ");

s2.concat(s1);

s1 += "winter ";

System.out.println(s1 + " " + s2);

• Possíveis questionamentos:– Qual a saída? Quantos objetos foram criados?

Quantos estão perdidos?

Page 12: String e IO

Strings: Fatos importantes sobre memória

• Área especial na memória: String constant pool

• Referências iguais, objetos iguais• Para evitar problemas com a

imutabilidade, a classe String é definida como f inal

Page 13: String e IO

Strings: Fatos importantes sobre memória

• Qual a diferença na memória entre os dois métodos a seguir?

String s = "abc";

String s = new String("abc");

Page 14: String e IO

Strings: Fatos importantes sobre memória

• Qual a diferença na memória entre os dois métodos a seguir?

String s = "abc";

String s = new String("abc");

Pelo fato de utilizarmos o new,um novo objeto String será criado na memória normal, e “abc” será criado na pool

Page 15: String e IO

Strings: Métodos importantes• Métodos importantes da classe String

■charAt() Returns the character located at the specif ied index ■concat() Appends one String to the end of another ( "+ " also works)

■equalsIgnoreCase() Determines the equality of two Strings, ignoring case

■ length() Returns the number of characters in a String ■replace() Replaces occurrences of a character with a new character ■substring() Returns a part of a String ■ toLowerCase() Returns a String with uppercase characters converted

■ toString() Returns the value of a String ■ toUpperCase() Returns a String with lowercase characters converted

■ trim() Removes whitespace from the ends of a String

Page 16: String e IO

Strings: Erros comuns

• Erros comuns– O atributo length

• Exemplo:String x = "test";

System.out.println( x.length );

ou

String[] x = new String[3];

System.out.println( x.length() );

• Qual desses códigos funcionará?

Page 17: String e IO

Strings: StringBuffer e StringBuilder

• StringBuffer x StringBuilder– As duas apresentam a mesma API– StringBuilder não apresenta métodos

sincronizados– A Sun recomenda StringBuilder pela sua

velocidade

Page 18: String e IO

Strings: StringBuffer e StringBuilder

• Exemplo inicialStringBuffer sb = new StringBuffer("abc");

sb.append("def");

System.out.println("sb = " + sb);

sb = new StringBuilder("abc");

sb.append("def").reverse().insert(3, "---");

System.out.println( sb );

– Qual será a saída?

Page 19: String e IO

Strings: StringBuffer e StringBuilder

• Exemplo inicialStringBuffer sb = new StringBuffer("abc");

sb.append("def");

System.out.println("sb = " + sb);

sb = new StringBuilder("abc");

sb.append("def").reverse().insert(3, "---");

System.out.println( sb );

– Qual será a saída?sb = abcdef

fed---cba

Page 20: String e IO

Strings: StringBuffer e StringBuilder

• Métodos importantes– public synchronized StringBuffer append(String s)– public StringBuilder delete(int start , int end)– public StringBuilder insert(int offset, String s)– public synchronized StringBuffer reverse( )– public synchronized StringBuffer toString( )

Page 21: String e IO

I/ O

• Navegação entre arquivos• Leitura de arquivos

Page 22: String e IO

I/ O

• Navegação entre arquivos• Leitura de arquivos

Page 23: String e IO

I/ O

Page 24: String e IO

I/ O• Exemplo Geral

import java.io.*;class Writer2 {

public static void main(String [] args) {char[] in = new char[50];int size = 0;try {

File f ile = new File("fileWrite2.txt");FileWriter fw = new FileWriter(file);fw.write("howdy\ nfolks\ n");fw.f lush();fw.close();FileReader fr = new FileReader(file); size = fr.read(in);System.out.print(size + " ");for(char c : in) System.out.print(c);fr.close();

} catch(IOException e) { }}

}– Qual será a saída?

Page 25: String e IO

I/ O• Exemplo Geral

import java.io.*;class Writer2 {

public static void main(String [] args) {char[] in = new char[50];int size = 0;try {

File file = new File("fileWrite2.txt");FileWriter fw = new FileWriter(file);fw.write("howdy\nfolks\n");fw.flush();fw.close();FileReader fr = new FileReader(file); size = fr.read(in);System.out.print(size + " ");for(char c : in) System.out.print(c);fr.close();

} catch(IOException e) { }}

}

– Qual será a saída? 12 howdyfolks

Page 26: String e IO

I/ O

• Exemplo com diretórioFile myDir = new File("mydir");

myDir.mkdir();

File myFile = new File(myDir,"myFile.txt");

myFile.createNewFile();

PrintWriter pw = new PrintWriter(myFile);

pw.println("new stuff");

pw.flush();

pw.close();

Page 27: String e IO

I/ O

• Exemplo com diretórioFile myDir = new File("mydir");

File myFile = new File(myDir,"myFile.txt");

myFile.createNewFile();

O que ocorrerá?

Page 28: String e IO

I/ O

• Exemplo com diretórioFile myDir = new File("mydir");

File myFile = new File(myDir,"myFile.txt");

myFile.createNewFile();

O que ocorrerá?

java.io.IOException: No such file or directory

Page 29: String e IO

I/ O• Exemplo com outros métodos

File delDir = new File("deldir");delDir.mkdir();File delFile1 = new File(delDir, "delFile1.txt");delFile1.createNewFile();File delFile2 = new File(delDir, "delFile2.txt"); delFile2.createNewFile();delFile1.delete();System.out.println("delDir is "+ delDir.delete()); File newName = new File(delDir, "newName.txt");delFile2.renameTo(newName); // rename fileFile newDir = new File("newDir");delDir.renameTo(newDir);

Saída:delDir is false

Page 30: String e IO

I/ O: Console Class

• Classe para tratar o console• Sempre invoca System.console()• Métodos importantes:

– readLine();– readPassword();

Page 31: String e IO

I/ O: Console Class• Exemplo

import java.io.Console;public class NewConsole {

public static void main(String[] args) {Console c = System.console();char[] pw;pw = c.readPassword("%s", "pw: ");for(char ch: pw)c.format("%c ", ch);c.format("\n");MyUtility mu = new MyUtility();while(true) {

String name = c.readLine("%s", "input?: ");c.format("output: %s \n", mu.doStuff(name));

}}

}

class MyUtility {String doStuff(String arg1) {

return "result is " + arg1;}

}