I created a txt. file (vector [14]) , it's a list of 14 countries that I need to print (all of them) using JOptionPane or similiar, but all appers to me is the first country. Someone can help me please?
public static void main (String [] args) throws IOException {
int cont=0;
BufferedReader fr= new BufferedReader (new FileReader("paises.txt")) ;
String destino= JOptionPane.showInputDialog("Digite o seu país de destino:");
String busca = destino;
try {
while (fr.ready()) {
String linha= fr.readLine();
if(linha.equals(busca)) {
cont =1;
}
}
fr.close();
if (cont==1) {
JOptionPane.showMessageDialog(null,"OK!","Opção Destinos",JOptionPane.INFORMATION_MESSAGE) ;
} else {
int res =JOptionPane.showConfirmDialog(null,"Destino não encontrado, gostaria de visualizar todos os países que fazem parte da nossa rota?","Ops!!",JOptionPane.YES_NO_CANCEL_OPTION);
if (res==JOptionPane.YES_OPTION) {
Scanner inFile = new Scanner(new FileReader("paises.txt"));
String pp = inFile.nextLine();
JOptionPane.showMessageDialog(null,pp, "Próxima Parada", JOptionPane.INFORMATION_MESSAGE);
}
}
}
catch (Exception e) {
System.out.println ("ERRO");
}
}
}
Related
Hi i have a jtable in witch i want to save and load from a txtfile.
Now i have achived that but now im wondering in witch manner could i import the data into a already created arraylist.
Import Code
String filePath = "C:\\Users\\ellim\\Desktop\\TitanPanel\\TitanPanel.txt";
File file = new File(filePath);
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
DefaultTableModel model = (DefaultTableModel) tbl_panels.getModel();
Object[] lines = br.lines().toArray();
for (int i = 0; i < lines.length; i++) {
String[] row = lines[i].toString().split(" ");
model.addRow(row);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(PanelTable.class.getName()).log(Level.SEVERE, null, ex);
}
Export Code
String filePath = "C:\\Users\\ellim\\Desktop\\TitanPanel\\TitanPanel.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < tbl_panels.getRowCount(); i++) {
for (int j = 0; j < tbl_panels.getColumnCount(); j++) {
bw.write(tbl_panels.getValueAt(i, j).toString() + " ");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(PanelTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
Arraylist i want to save into
ArrayList documentos;
Here is code for ArrayList export
ArrayList<String> documentos = new ArrayList<String>();
// here i am using , as separator
ArrayListExporter exporter = new ArrayListExporter ( documentos , "," );
exporter.export( tbl_panels );
public interface TableDataExporter {
public void export( JTable table );
}
public class FileExporter implements TableDataExporter {
private String fileName;
private String separator ;
public FileExporter( String fileName,String separator ) {
this.fileName=fileName;
this.separator=separator;
}
public void export( JTable table ) {
File file = new File(fileName);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < tbl_panels.getRowCount(); i++) {
for (int j = 0; j < tbl_panels.getColumnCount(); j++) {
if( j != 0 ) {
bw.write( separator );
}
bw.write(tbl_panels.getValueAt(i, j).toString() );
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(PanelTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class ArrayListExporter implements TableDataExporter {
private List<String> list;
private String separator;
public FileExporter( List<String> list,String separator ) {
this.list=list;
this.separator=separator;
}
public void export( JTable table ) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < tbl_panels.getRowCount(); i++) {
builder.delete(0,builder.length());
for (int j = 0; j < tbl_panels.getColumnCount(); j++) {
if( j != 0 ) {
builder.append( separator );
}
Object obj = tbl_panels.getValueAt(i, j);
builder.append( obj == null ? "null" : obj.toString() );
}
}
}
}
So right now I'm making a mod in Minecraft where it takes everyones username from a server and adds it to a txt file, it works but the the problem is I don't want to duplicate the names when I use the command again. Nothing has worked so far. How would I check if the txt already contains the username, don't add it again? Thank you. Again, I need it to before writing another name to the list, check the txt file if it already contains the name, if so don't add it.
[code]
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
try {
fileWriter = new FileWriter(GameDirectory() + "\\scraped.txt", true);
bufferedReader = new BufferedReader(new FileReader(GameDirectory() + "\\scraped.txt"));
lineNumberReader = new LineNumberReader(new FileReader(GameDirectory() + "\\scraped.txt"));
} catch (IOException e) {
e.printStackTrace();
}
printWriter = new PrintWriter(fileWriter);
try {
fileWriter.write(playerName + "\r\n");
lineNumberReader.skip(Long.MAX_VALUE);
} catch (IOException e) {
e.printStackTrace();
}
printWriter.flush();
}
addMessage("Scraped " + lineNumberReader.getLineNumber() + " usernames!");
}
[/code]
I've tried this too but with this it doesn't even write anymore.
[code]
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
String lines;
try {
if ((lines = bufferedReader.readLine()) != null) {
if (!lines.contains(playerName)) {
bufferedWriter.write(playerName);
bufferedWriter.newLine();
bufferedWriter.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
int linenumber = 0;
try {
while (lineNumberReader.readLine() != null) {
linenumber++;
}
} catch (IOException e) {
e.printStackTrace();
}
[/code]
I am having trouble creating a method to import data from a txt file into a 1d string array and a 2d double array.
Here is what I have thus far:
public static void main(String[] args){
String[] productName = new String[100];
double[][] sales = new double[100][5];
initializeArrays(productName, sales);
....}
public static void initializeArrays(String a[], double b[][]){
try
{
String output = "";
File inputFile = new File("c:/temp/salesdata.txt");
if (inputFile.exists())
{
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNext())
{
for (i=1;i<6;i++)
{
b[a.length][i]=scanner.nextDouble();
}
rowCount += 1;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Error reading file: ");
}
Try this code:
public static void initializeArrays(String a[], double b[][]){
try
{
String output = "";
File inputFile = new File("c:/temp/salesdata.txt");
int counter = 0;
if (inputFile.exists())
{
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNext())
{
for (i=1;i<6;i++)
{
b[counter][i]=scanner.nextDouble();
}
counter++;
rowCount += 1;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Error reading file: ");
}
I am trying to write a method that prints information into an array. the directions are: Create a second method for WordPath:
makeWordArray that takes a String file name as input, and it returns either an array or an ArrayList that stores WordData objects.
First, the method should open the file with new FileReader(file), call the numLines method to get the number of lines in file, and then create an array or an ArrayList of that size.
Next, close the FileReader and reopen the file. This time use BufferedReader br = new BufferedReader(new FileReader(file)). Create a loop to run through the file calling br.readLine(). For each line that you read in from br.readLine(), call the parseWordData on that String to get a WordData and store the WordData object into the appropriate index of the array or ArrayList.
My code is:
public class WordPath {
public static int numLines(Reader reader) {
BufferedReader br = new BufferedReader(reader);
int lines = 0;
try {
while(br.readLine() != null) {
lines = lines + 1;
}
br.close();
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
return lines;
}
public WordData[] makeWordArray(String file) {
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
WordData[] newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
}
I am running int a problem where the variable newArray can not be found, I believe because it is in the try statement. Is there any way to reformat this to work?
Like this:
public WordData[] makeWordArray(String file) {
WordData[] newArray = null;
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
You need to pull the declaration of the variable outside, but leave the assignment to that variable on the inside of the try.
I have problem with loading image from database to jsp view. It looks like action are execute but stop in middle.
I log when execute() method start and when its end. In log file i can see start this method but there are no end.
I have action:
public class ShowImageAction extends BaseAction {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(ShowImageAction.class);
private int id;
public String execute() {
LOG.info("Enter execute()");
MessageBean messageBean = (MessageBean) sessionParameters
.get(SessionParameters.BANNER_EDIT);
IFiles filesEJB = EJBLocator.getFiles();
if (messageBean != null) {
id = messageBean.getBannerId();
}
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
bytes = FileUtils.readFileToByteArray(file.getImage());
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
LOG.info("Exit execute()");
return NONE;
}
jsp:
<div class="OneFilteringRow">
Podgląd<br />
<img src="/ebok-bm/ShowImageAction" alt="Podgląd banera" />
</div>
struts.xml
<action name="ShowImageAction"
class="pl.bm.action.content.ShowImageAction">
</action>
Problem was in:
FileBean file = filesEJB.file(id);
I get bytes from database and try to save it to tmpFile. Now I get bytes and writes them to a temporary file and immediately transmit it to the action and everything is ok.
Now I have:
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
**bytes = file.getImage();**
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
}
Switch to your own result implements Result class and write output here.Other in struts.xmlaction result type specified own with approx mate parameters.
refer:generate own image as action result