Strings e I/ O
Grupo de estudo para SCJP
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
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";
Strings: Métodos e referências
• Métodos e referências
Strings: Métodos e referências
• Métodos e referências
Strings: Métodos e referências
• Métodos e referências
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?
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
Strings: Métodos e referências
• Outro exemploString x = "Java";
x = x.concat(" Rules!");
System.out.println("x = " + x);
– E agora?
Strings: Métodos e referências
• Outro exemploString x = "Java";
x = x.concat(" Rules!");
System.out.println("x = " + x);
– E agora? x = Java Rules!
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?
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
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");
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
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
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á?
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
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?
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
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( )
I/ O
• Navegação entre arquivos• Leitura de arquivos
I/ O
• Navegação entre arquivos• Leitura de arquivos
I/ O
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?
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
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();
I/ O
• Exemplo com diretórioFile myDir = new File("mydir");
File myFile = new File(myDir,"myFile.txt");
myFile.createNewFile();
O que ocorrerá?
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
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
I/ O: Console Class
• Classe para tratar o console• Sempre invoca System.console()• Métodos importantes:
– readLine();– readPassword();
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;}
}
Top Related