Método java para gerar um hash MD5. Veja como gerar um hash MD5 em java:
/**
* Gera um hash MD5 a partir da senha passada por parâmetro
*
* @param senha
* @return String - o hash gerado
* @throws NoSuchAlgorithmException
*/
public static String gerarHashMD5(String senha) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(senha.getBytes());
byte[] byteDigest = digest.digest();
String res = "";
for (int i = 0; i < byteDigest.length; ++i) {
String aux = Integer.toHexString((byteDigest[i] & 0xFF));
if (aux.length() == 1) {
aux = '0' + aux;
}
res += aux;
}
return res;
}
Blog de Programação, TI, mobile, análise de sistemas
e desenvolvimento de software em geral.
Mostrando postagens com marcador javautils. Mostrar todas as postagens
Mostrando postagens com marcador javautils. Mostrar todas as postagens
terça-feira, 10 de agosto de 2010
sexta-feira, 30 de julho de 2010
[javautils] moveFile
/**
* Move um arquivo
*
* @param filenameSource
* @param filenameDestiny
*/
public static void moveFile(String filenameSource, String filenameDestiny) {
try {
JavaUtils.copyFile(filenameSource, filenameDestiny);
JavaUtils.deleteFile(filenameSource, false);
} catch (Throwable e) {
try {
JavaUtils.deleteFile(filenameDestiny, true);
} catch (Throwable e1) {
}
throw new RuntimeException(
"JavaUtils.moveFile() - Erro desconhecido ao mover o arquivo de \"" +
filenameSource + "\" para \"" + filenameDestiny + "\". Error: " + e);
}
}
* Move um arquivo
*
* @param filenameSource
* @param filenameDestiny
*/
public static void moveFile(String filenameSource, String filenameDestiny) {
try {
JavaUtils.copyFile(filenameSource, filenameDestiny);
JavaUtils.deleteFile(filenameSource, false);
} catch (Throwable e) {
try {
JavaUtils.deleteFile(filenameDestiny, true);
} catch (Throwable e1) {
}
throw new RuntimeException(
"JavaUtils.moveFile() - Erro desconhecido ao mover o arquivo de \"" +
filenameSource + "\" para \"" + filenameDestiny + "\". Error: " + e);
}
}
[javautils] deleteFile
/**
* Exclui um arquivo (e seus subdiretorios e sub arquivos, se ele for um diretorio)
*
* @param filename
* @param silent - se true, não gera nenhuma exceção mesmo que não consiga excluir o arquivo
*/
public static void deleteFile(String filename, boolean silent) {
File arquivo = new File(filename);
/*
* Se o arquivo não for um diretório, é deletado. Caso seja um diretório, é deletado com
* seus subdiretórios e arquivos.
*/
if (!arquivo.isDirectory()) {
JavaUtils.subDeleteFile(filename, silent, arquivo);
} else {
File[] listFiles = arquivo.listFiles();
for (int i = 0; i < listFiles.length; i++) {
File arquivoFilho = listFiles[i];
JavaUtils.deleteFile(arquivoFilho.getAbsolutePath(), silent);
}
JavaUtils.subDeleteFile(filename, silent, arquivo);
}
}
/**
* Usado pelo deleteFile. Tenta apagar o arquivo e faz o tratamento de exceção.
*
* @param filename
* @param silent
* @param arquivo
*/
protected static void subDeleteFile(String filename, boolean silent, File arquivo) {
boolean excluiu = false;
try {
excluiu = arquivo.delete();
} catch (Throwable e) {
if (!silent) {
// Se silent for false, gera exceção.
throw new RuntimeException(
"JavaUtils.deleteFile() - Erro desconhecido ao excluir o arquivo \"" +
filename + "\". Error: " + e);
}
}
if (!excluiu && !silent) {
//Se não conseguir excluir o arquivo, gera exceção.
throw new RuntimeException(
"JavaUtils.deleteFile() - Erro desconhecido. Não conseguiu excluir o arquivo com o nome \"" +
filename +
"\". Pode ser que o arquivo não exista, por isso o erro.");
}
}
* Exclui um arquivo (e seus subdiretorios e sub arquivos, se ele for um diretorio)
*
* @param filename
* @param silent - se true, não gera nenhuma exceção mesmo que não consiga excluir o arquivo
*/
public static void deleteFile(String filename, boolean silent) {
File arquivo = new File(filename);
/*
* Se o arquivo não for um diretório, é deletado. Caso seja um diretório, é deletado com
* seus subdiretórios e arquivos.
*/
if (!arquivo.isDirectory()) {
JavaUtils.subDeleteFile(filename, silent, arquivo);
} else {
File[] listFiles = arquivo.listFiles();
for (int i = 0; i < listFiles.length; i++) {
File arquivoFilho = listFiles[i];
JavaUtils.deleteFile(arquivoFilho.getAbsolutePath(), silent);
}
JavaUtils.subDeleteFile(filename, silent, arquivo);
}
}
/**
* Usado pelo deleteFile. Tenta apagar o arquivo e faz o tratamento de exceção.
*
* @param filename
* @param silent
* @param arquivo
*/
protected static void subDeleteFile(String filename, boolean silent, File arquivo) {
boolean excluiu = false;
try {
excluiu = arquivo.delete();
} catch (Throwable e) {
if (!silent) {
// Se silent for false, gera exceção.
throw new RuntimeException(
"JavaUtils.deleteFile() - Erro desconhecido ao excluir o arquivo \"" +
filename + "\". Error: " + e);
}
}
if (!excluiu && !silent) {
//Se não conseguir excluir o arquivo, gera exceção.
throw new RuntimeException(
"JavaUtils.deleteFile() - Erro desconhecido. Não conseguiu excluir o arquivo com o nome \"" +
filename +
"\". Pode ser que o arquivo não exista, por isso o erro.");
}
}
[javautils] createFile
/**
* Cria um novo arquivo vazio
*
* @param filename
* @param overwrite - se true, recria o arquivo mesmo que ele já exista
*/
public static void createFile(String filename, boolean overwrite) {
try {
boolean criou = false;
File file = new File(filename);
criou = file.createNewFile();
if (!criou && overwrite) {
JavaUtils.writeFile(filename, new StringBuffer());
} else if (!criou) {
throw new RuntimeException(
"JavaUtils.createFile() - Erro desconhecido. Não conseguiu criar o arquivo com o nome \"" +
filename +
"\". Pode ser que o arquivo já esteja criado, por isso o erro.");
}
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.createFile() - Erro desconhecido ao criar o arquivo \"" +
filename + "\". Error: " + e);
}
}
* Cria um novo arquivo vazio
*
* @param filename
* @param overwrite - se true, recria o arquivo mesmo que ele já exista
*/
public static void createFile(String filename, boolean overwrite) {
try {
boolean criou = false;
File file = new File(filename);
criou = file.createNewFile();
if (!criou && overwrite) {
JavaUtils.writeFile(filename, new StringBuffer());
} else if (!criou) {
throw new RuntimeException(
"JavaUtils.createFile() - Erro desconhecido. Não conseguiu criar o arquivo com o nome \"" +
filename +
"\". Pode ser que o arquivo já esteja criado, por isso o erro.");
}
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.createFile() - Erro desconhecido ao criar o arquivo \"" +
filename + "\". Error: " + e);
}
}
[javautils] copyFile
/**
* Faz a cópia de um arquivo
*
* @param filenameSource
* @param filenameDestiny
*/
public static void copyFile(String filenameSource, String filenameDestiny) {
try {
// Cria a stream para ler o arquivo original
FileInputStream fin = new FileInputStream(filenameSource);
// Cria a stream para gravar o arquivo de cópia
FileOutputStream fout = new FileOutputStream(filenameDestiny);
// Usa as streams para criar os canais correspondentes
FileChannel in = fin.getChannel();
FileChannel out = fout.getChannel();
// Número de bytes do arquivo original
long numbytes = in.size();
// Transfere todo o volume para o arquivo de cópia.
in.transferTo(0, numbytes, out);
out.close();
in.close();
fout.close();
fin.close();
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.copyFile() - Erro desconhecido ao copiar o arquivo \"" +
filenameSource + "\" para \"" + filenameDestiny + "\". Error: " + e);
}
}
[javautils] readFileAsStringBuffer
/**
* Lê o texto de um arquivo
*
* @param filename
* @return StringBuffer - Um StringBuffer com todo o texto do arquivo
*/
public static StringBuffer readFileAsStringBuffer(String filename) {
StringBuffer texto = new StringBuffer();
try {
FileReader reader = new FileReader(filename);
BufferedReader in = new BufferedReader(reader);
String linha = null;
long count = 0;
while ((linha = in.readLine()) != null) {
if (count == 0) {
texto.append(linha);
count++;
} else {
texto.append("\n");
texto.append(linha);
}
}
in.close();
reader.close();
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.readFileAsStringBuffer() - Erro desconhecido ao ler o arquivo \"" +
filename + "\". Error: " + e);
}
return texto;
}
* Lê o texto de um arquivo
*
* @param filename
* @return StringBuffer - Um StringBuffer com todo o texto do arquivo
*/
public static StringBuffer readFileAsStringBuffer(String filename) {
StringBuffer texto = new StringBuffer();
try {
FileReader reader = new FileReader(filename);
BufferedReader in = new BufferedReader(reader);
String linha = null;
long count = 0;
while ((linha = in.readLine()) != null) {
if (count == 0) {
texto.append(linha);
count++;
} else {
texto.append("\n");
texto.append(linha);
}
}
in.close();
reader.close();
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.readFileAsStringBuffer() - Erro desconhecido ao ler o arquivo \"" +
filename + "\". Error: " + e);
}
return texto;
}
quarta-feira, 28 de julho de 2010
[javautils] writeFile
/**
* Escreve um texto no arquivo (sobrescrevendo todo o texto que já existia nele)
*
* @param filename
* @param texto
*/
public static void writeFile(String filename, String texto) {
try {
FileWriter writer = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(writer);
out.write(texto);
out.close();
writer.close();
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.writeFile(String, String) - Erro desconhecido ao escrever um texto no arquivo \"" +
filename + "\". Error: " + e);
}
}
* Escreve um texto no arquivo (sobrescrevendo todo o texto que já existia nele)
*
* @param filename
* @param texto
*/
public static void writeFile(String filename, String texto) {
try {
FileWriter writer = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(writer);
out.write(texto);
out.close();
writer.close();
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.writeFile(String, String) - Erro desconhecido ao escrever um texto no arquivo \"" +
filename + "\". Error: " + e);
}
}
[javautils] appendFile
/**
* Escreve um texto no final do arquivo (append)
*
* @param filename
* @param texto
*/
public static void appendFile(String filename, String texto) {
try {
FileWriter writer = new FileWriter(filename, true);
BufferedWriter out = new BufferedWriter(writer);
out.write(texto);
out.close();
writer.close();
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.appendFile(String, String) - Erro desconhecido ao escrever um texto no final do arquivo \"" +
filename + "\". Error: " + e);
}
}
* Escreve um texto no final do arquivo (append)
*
* @param filename
* @param texto
*/
public static void appendFile(String filename, String texto) {
try {
FileWriter writer = new FileWriter(filename, true);
BufferedWriter out = new BufferedWriter(writer);
out.write(texto);
out.close();
writer.close();
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.appendFile(String, String) - Erro desconhecido ao escrever um texto no final do arquivo \"" +
filename + "\". Error: " + e);
}
}
[javautils] convertCollectionToSqlINClause
/**
* Converte uma coleção qualquer em um formato que possa ser colocado em uma cláusula SQL
* "IN".
*
* Ex: dada uma coleção da seguinte forma:
*
* Collection textoColecao = new ArrayList();
* textoColecao.add("primeiro");
* textoColecao.add("segundo");
* textoColecao.add("terceiro");
*
*
* A chamada em uma clásula IN ficaria assim:
*
*
* StringBuffer sql = new StringBuffer();
* sql.append("select * from algo where algo.id in ( ");
* sql.append(JavaUtils.convertCollectionToSqlINClause(textoColecao);
* sql.append(" ) ");
*
*
* O resultado da sql montada será:
*
*
* select * from algo where algo.id in ( primeiro, segundo, terceiro )
*
* @param colecao
* @return String
*/
public static String convertCollectionToSqlINClause(Collection colecao) {
try {
StringBuffer buffer = new StringBuffer();
Iterator iterator = colecao.iterator();
Object primeiroItem = iterator.next();
buffer.append(primeiroItem.toString());
while (iterator.hasNext()) {
Object item = iterator.next();
buffer.append("," + item);
}
return buffer.toString();
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.convertCollectionToSqlINClause() - Error on convert the collection \"" +
colecao +
"\" with size \"" +
((colecao == null) ? null : colecao.size()) +
"\" in a sql \"IN\" clause. Error details: " + e);
}
}
* Converte uma coleção qualquer em um formato que possa ser colocado em uma cláusula SQL
* "IN".
*
* Ex: dada uma coleção da seguinte forma:
*
* Collection textoColecao = new ArrayList();
* textoColecao.add("primeiro");
* textoColecao.add("segundo");
* textoColecao.add("terceiro");
*
*
* A chamada em uma clásula IN ficaria assim:
*
*
* StringBuffer sql = new StringBuffer();
* sql.append("select * from algo where algo.id in ( ");
* sql.append(JavaUtils.convertCollectionToSqlINClause(textoColecao);
* sql.append(" ) ");
*
*
* O resultado da sql montada será:
*
*
* select * from algo where algo.id in ( primeiro, segundo, terceiro )
*
* @param colecao
* @return String
*/
public static String convertCollectionToSqlINClause(Collection colecao) {
try {
StringBuffer buffer = new StringBuffer();
Iterator iterator = colecao.iterator();
Object primeiroItem = iterator.next();
buffer.append(primeiroItem.toString());
while (iterator.hasNext()) {
Object item = iterator.next();
buffer.append("," + item);
}
return buffer.toString();
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.convertCollectionToSqlINClause() - Error on convert the collection \"" +
colecao +
"\" with size \"" +
((colecao == null) ? null : colecao.size()) +
"\" in a sql \"IN\" clause. Error details: " + e);
}
}
terça-feira, 27 de julho de 2010
[java] convertStringDecimalToBigDecimal
/**
* Converte uma String no formato decimal (valor de moeda, p. ex.) para um BigDecimal.
* Se a String for vazia ou se ocorrer uma exceção, retorna null
*
* @param valor
* @param locale - pegue o Locale desejado pelo método "getLocale..." do JavaUtils
* @return String
*/
public static BigDecimal convertStringDecimalToBigDecimal(String valor, Locale locale,
int minimoCasasDecimais, int maximoCasasDecimais) {
BigDecimal retorno = null;
if (JavaUtils.isStringNaoVazia(valor)) {
try {
NumberFormat formato = DecimalFormat.getNumberInstance(locale);
formato.setMinimumFractionDigits(minimoCasasDecimais);
formato.setMaximumFractionDigits(maximoCasasDecimais);
retorno = new BigDecimal(formato.parse(valor).doubleValue());
} catch (Throwable e) {
log.warn("JavaUtils.convertStringDecimalToBigDecimal() - Erro de " +
"conversao. Vai retornar null. Error: " + e);
}
}
return retorno;
}
* Converte uma String no formato decimal (valor de moeda, p. ex.) para um BigDecimal.
* Se a String for vazia ou se ocorrer uma exceção, retorna null
*
* @param valor
* @param locale - pegue o Locale desejado pelo método "getLocale..." do JavaUtils
* @return String
*/
public static BigDecimal convertStringDecimalToBigDecimal(String valor, Locale locale,
int minimoCasasDecimais, int maximoCasasDecimais) {
BigDecimal retorno = null;
if (JavaUtils.isStringNaoVazia(valor)) {
try {
NumberFormat formato = DecimalFormat.getNumberInstance(locale);
formato.setMinimumFractionDigits(minimoCasasDecimais);
formato.setMaximumFractionDigits(maximoCasasDecimais);
retorno = new BigDecimal(formato.parse(valor).doubleValue());
} catch (Throwable e) {
log.warn("JavaUtils.convertStringDecimalToBigDecimal() - Erro de " +
"conversao. Vai retornar null. Error: " + e);
}
}
return retorno;
}
[java] isBigDecimalVazio
/**
* Verifica se o BigDecimal está vazio (se é null ou igual a 0)
*
* @param valor
* @return boolean
*/
public static boolean isBigDecimalVazio(BigDecimal valor) {
try {
BigDecimal zero = new BigDecimal(0);
if (valor.compareTo(zero) == 0) {
// se o numero eh igual a 0 (zero) retorna true
return true;
}
} catch (NullPointerException e) {
// se o numero eh null, retorna true
return true;
}
return false;
}
[java] convertBigDecimalToStringDecimal
/**
* Converte um BigDecimal para uma String no formato
* decimal (valor de moeda, p. ex.). Se o
* BigDecimal for vazio ou se ocorrer uma exceção,
* retorna uma String vazia ("")
*
* @param valor
* @param locale - pegue o Locale desejado pelo
* método "getLocale..." do JavaUtils
* @param minimoCasasDecimais
* @param maximoCasasDecimais
* @return String
*/
public static String convertBigDecimalToStringDecimal(BigDecimal valor, Locale locale,
int minimoCasasDecimais, int maximoCasasDecimais) {
String retorno = "";
if (JavaUtils.isBigDecimalNaoVazio(valor)) {
try {
NumberFormat formato = DecimalFormat.getNumberInstance(locale);
formato.setMinimumFractionDigits(minimoCasasDecimais);
formato.setMaximumFractionDigits(maximoCasasDecimais);
retorno = formato.format(valor);
} catch (Throwable e) {
log.warn("JavaUtils.convertBigDecimalToStringDecimal() - Erro de " +
"conversao. Vai retornar \"\". Error: " + e);
}
}
return retorno;
}
* Converte um BigDecimal para uma String no formato
* decimal (valor de moeda, p. ex.). Se o
* BigDecimal for vazio ou se ocorrer uma exceção,
* retorna uma String vazia ("")
*
* @param valor
* @param locale - pegue o Locale desejado pelo
* método "getLocale..." do JavaUtils
* @param minimoCasasDecimais
* @param maximoCasasDecimais
* @return String
*/
public static String convertBigDecimalToStringDecimal(BigDecimal valor, Locale locale,
int minimoCasasDecimais, int maximoCasasDecimais) {
String retorno = "";
if (JavaUtils.isBigDecimalNaoVazio(valor)) {
try {
NumberFormat formato = DecimalFormat.getNumberInstance(locale);
formato.setMinimumFractionDigits(minimoCasasDecimais);
formato.setMaximumFractionDigits(maximoCasasDecimais);
retorno = formato.format(valor);
} catch (Throwable e) {
log.warn("JavaUtils.convertBigDecimalToStringDecimal() - Erro de " +
"conversao. Vai retornar \"\". Error: " + e);
}
}
return retorno;
}
[java] getLocaleEUA
/**
* Retorna o Locale dos Estados Unidos
*
* @return Locale
*/
public static Locale getLocaleEUA() {
return Locale.ENGLISH;
}
* Retorna o Locale dos Estados Unidos
*
* @return Locale
*/
public static Locale getLocaleEUA() {
return Locale.ENGLISH;
}
[java] getLocaleBrasil
/**
* Retorna o Locale do Brasil
*
* @return Locale
*/
public static Locale getLocaleBrasil() {
return new Locale("pt", "BR");
}
* Retorna o Locale do Brasil
*
* @return Locale
*/
public static Locale getLocaleBrasil() {
return new Locale("pt", "BR");
}
[java] isBigDecimalNaoVazio
/**
* Verifica se o BigDecimal não está vazio (se não é null nem igual a 0)
*
* @param valor
* @return boolean
*/
public static boolean isBigDecimalNaoVazio(BigDecimal valor) {
return !JavaUtils.isBigDecimalVazio(valor);
}
* Verifica se o BigDecimal não está vazio (se não é null nem igual a 0)
*
* @param valor
* @return boolean
*/
public static boolean isBigDecimalNaoVazio(BigDecimal valor) {
return !JavaUtils.isBigDecimalVazio(valor);
}
domingo, 25 de julho de 2010
[java] convertStringArrayToIntArray
convertendo um array de strings de em um array de int:
/**
* The function stringArrayToIntArray takes as input a String array which is assumed to
* contain Strings that represent ints. It returns an int array containing the ints
* represented by each String from the String array.
*
* @param s
* @return int[]
*/
public static int[] convertStringArrayToIntArray(String[] s) {
try {
int[] intArray;
try {
intArray = new int[s.length];
} catch (NullPointerException e2) {
return null;
}
for (int i = 0; i < s.length; i++) { try {
intArray[i] = Integer.parseInt(s[i]);
} catch (Throwable e) {
try {
if (s[i].equals("")) {
intArray[i] = 0;
continue;
}
} catch (NullPointerException e1) {
intArray[i] = 0;
continue;
}
throw e;
}
}
return intArray;
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.convertStringArrayToIntArray() - Error on convert the String array \"" +
s + "\" to an int array. Error details: " + e);
}
}
/**
* The function stringArrayToIntArray takes as input a String array which is assumed to
* contain Strings that represent ints. It returns an int array containing the ints
* represented by each String from the String array.
*
* @param s
* @return int[]
*/
public static int[] convertStringArrayToIntArray(String[] s) {
try {
int[] intArray;
try {
intArray = new int[s.length];
} catch (NullPointerException e2) {
return null;
}
for (int i = 0; i < s.length; i++) { try {
intArray[i] = Integer.parseInt(s[i]);
} catch (Throwable e) {
try {
if (s[i].equals("")) {
intArray[i] = 0;
continue;
}
} catch (NullPointerException e1) {
intArray[i] = 0;
continue;
}
throw e;
}
}
return intArray;
} catch (Throwable e) {
throw new RuntimeException(
"JavaUtils.convertStringArrayToIntArray() - Error on convert the String array \"" +
s + "\" to an int array. Error details: " + e);
}
}
domingo, 2 de maio de 2010
Java - Convertendo um String pra Date
Método Java para converter um String para Date.
A vantagem deste método é que se o padrão for dd/MM/yyyy e se o usuário digitar 17/10/10, o método converte o "10" para "2010" automaticamente.
public Date stringToDate(String string, String pattern)
throws Throwable {
Date data = null;
if (JavaUtils.isStringNaoVazia(string)) {
// Caso o padrão seja dia/mês/ano e o usuário tenha digitado o ano
// com dois dígitos. (Ex.: 07)
// o ano deve ser 2007
if (JavaUtils.isObjectsIguais("dd/MM/yyyy", pattern) && string.length() == 8) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(string.substring(0, 6));
stringBuffer.append("20");
stringBuffer.append(string.substring(6));
string = stringBuffer.toString();
}
// Caso o padrão seja mês/ano e o usuário tenha digitado o ano com dois
// dígitos. (Ex.: 07)
// o ano deve ser 2007
if (JavaUtils.isObjectsIguais("MM/yyyy", pattern) && string.length() == 5) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(string.substring(0, 3));
stringBuffer.append("20");
stringBuffer.append(string.substring(3));
string = stringBuffer.toString();
}
// Caso o padrão seja dia/mês/ano HH:mm e o usuário tenha digitado o ano
// com dois dígitos. (Ex.: 07)
// o ano deve ser 2007
if (JavaUtils.isObjectsIguais("dd/MM/yyyy HH:mm", pattern) && string.length() == 14) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(string.substring(0, 6));
stringBuffer.append("20");
stringBuffer.append(string.substring(6));
string = stringBuffer.toString();
}
// Caso o padrão seja mês/ano HH:mm e o usuário tenha digitado o ano
// com dois dígitos. (Ex.: 07)
// o ano deve ser 2007
if (JavaUtils.isObjectsIguais("MM/yyyy HH:mm", pattern) && string.length() == 11) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(string.substring(0, 3));
stringBuffer.append("20");
stringBuffer.append(string.substring(3));
string = stringBuffer.toString();
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setLenient(false);
data = sdf.parse(string);
}
return data;
}
A vantagem deste método é que se o padrão for dd/MM/yyyy e se o usuário digitar 17/10/10, o método converte o "10" para "2010" automaticamente.
public Date stringToDate(String string, String pattern)
throws Throwable {
Date data = null;
if (JavaUtils.isStringNaoVazia(string)) {
// Caso o padrão seja dia/mês/ano e o usuário tenha digitado o ano
// com dois dígitos. (Ex.: 07)
// o ano deve ser 2007
if (JavaUtils.isObjectsIguais("dd/MM/yyyy", pattern) && string.length() == 8) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(string.substring(0, 6));
stringBuffer.append("20");
stringBuffer.append(string.substring(6));
string = stringBuffer.toString();
}
// Caso o padrão seja mês/ano e o usuário tenha digitado o ano com dois
// dígitos. (Ex.: 07)
// o ano deve ser 2007
if (JavaUtils.isObjectsIguais("MM/yyyy", pattern) && string.length() == 5) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(string.substring(0, 3));
stringBuffer.append("20");
stringBuffer.append(string.substring(3));
string = stringBuffer.toString();
}
// Caso o padrão seja dia/mês/ano HH:mm e o usuário tenha digitado o ano
// com dois dígitos. (Ex.: 07)
// o ano deve ser 2007
if (JavaUtils.isObjectsIguais("dd/MM/yyyy HH:mm", pattern) && string.length() == 14) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(string.substring(0, 6));
stringBuffer.append("20");
stringBuffer.append(string.substring(6));
string = stringBuffer.toString();
}
// Caso o padrão seja mês/ano HH:mm e o usuário tenha digitado o ano
// com dois dígitos. (Ex.: 07)
// o ano deve ser 2007
if (JavaUtils.isObjectsIguais("MM/yyyy HH:mm", pattern) && string.length() == 11) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(string.substring(0, 3));
stringBuffer.append("20");
stringBuffer.append(string.substring(3));
string = stringBuffer.toString();
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setLenient(false);
data = sdf.parse(string);
}
return data;
}
Java - Métodos para verificar se dois objetos são diferentes e se são iguais
Dois métodos: um para verificar se dois objetos são diferentes ou não e outro para verificar se dois objetos são iguais:
public boolean isObjectsDiferentes(Object objeto1, Object objeto2) {
try {
if (objeto1.equals(objeto2)) {
return false;
}
} catch (NullPointerException e) {
try {
objeto2.toString();
} catch (NullPointerException e1) {
return false;
}
}
return true;
}
public boolean isObjectsDiferentes(Object objeto1, Object objeto2) {
try {
if (objeto1.equals(objeto2)) {
return false;
}
} catch (NullPointerException e) {
try {
objeto2.toString();
} catch (NullPointerException e1) {
return false;
}
}
return true;
}
public boolean isObjectsIguais(Object objeto1, Object objeto2) {
return ! isObjectsDiferentes;
}
Java - Método que verifica se uma String está vazia
Método que verifica se uma String está vazia ou se é null:
public boolean stringVazia(String texto) {
try {
// pega a primeira letra da palavra. se conseguir, eh porque a string não tah vazia.
// nesse caso retorna false.
texto.charAt(0);
return false;
} catch (NullPointerException e) {
// se o texto eh null, retorna true
return true;
} catch (StringIndexOutOfBoundsException e) {
// se o texto eh "", retorna true
return true;
}
}
public boolean stringVazia(String texto) {
try {
// pega a primeira letra da palavra. se conseguir, eh porque a string não tah vazia.
// nesse caso retorna false.
texto.charAt(0);
return false;
} catch (NullPointerException e) {
// se o texto eh null, retorna true
return true;
} catch (StringIndexOutOfBoundsException e) {
// se o texto eh "", retorna true
return true;
}
}
Java - Convertendo um Date para String
Método para converter um java.util.Date do Java para String:
public String dateToString(Date date, String pattern) {
String formatado;
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
formatado = sdf.format(date);
} catch (Throwable e) {
throw e;
}
}
Sendo que o parâmetro "pattern" deve ser de acordo com o que está escrito em http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html
Até mais
public String dateToString(Date date, String pattern) {
String formatado;
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
formatado = sdf.format(date);
} catch (NullPointerException e) {
return "";
} catch (Throwable e) {
throw e;
}
}
Sendo que o parâmetro "pattern" deve ser de acordo com o que está escrito em http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html
Até mais
Assinar:
Postagens (Atom)