Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm trying to make two basic functions which will allow me to call them from other classes in order to return a HashMap from the 'getAllData()' and to write to the file in 'writeToFile()', without any luck. I've been tampering with it for a while now and just getting a multitude of strange errors.
Code:
static HashMap<Integer ,String> getAllData(Integer choice) throws Exception{
InputStream localInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("Shadow.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(localInputStream));
if (choice.equals(1)){
while ((!data.equals(null))){
data = br.readLine();
dataString = dataString+data;
}
writeToFile(dataString);
br.close();
}return name;
}
static void writeToFile(String data) throws IOException{;
File file = new File ("Shadow.txt");
FileWriter fileWriter = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(data);
bw.newLine();
bw.flush();
bw.close();
}
With this current code, nothing happens. The file remains exactly how it is, although to me, the code should read everything from it, and then append it.
How can I fix this?
Thanks
This might help you:
static void getAllData(final Integer choice) throws Exception {
final BufferedReader br = new BufferedReader(new FileReader("Shadow.txt"));
String data = "";
final StringBuilder builder = new StringBuilder();
if(choice.equals(1)) {
while(data != null) {
data = br.readLine();
if(data != null) {
builder.append(data + "\n");
}
}
writeToFile(builder.toString());
br.close();
}
}
static void writeToFile(final String data) throws IOException {
final File file = new File("Shadow.txt");
final FileWriter fileWriter = new FileWriter(file, true);
final BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(data);
bw.flush();
bw.close();
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I've been getting an Array Index Out of Bounds Error.
Basically I have a file where a user name and password is saved lke this: user:password
I'm trying to read the file to check if a new user is already signed in or not. This is in a thread and also using a socket.
private void authentication(String user, String password) {
List<String> nomes = new ArrayList<>();
List<String> pass = new ArrayList<>();
BufferedReader reader;
try {
FileWriter fw = new FileWriter("users.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
BufferedReader br = new BufferedReader(new FileReader("users.txt"));
//String line;
String line;
while((line = br.readLine())!=null){
String[] pair = line.split(";");
nomes.add(pair[0]);
pass.add(pair[1]);
}
/*while ((line = br.readLine()) != null) {
String[] info = line.split(":");
System.out.println(line);
System.out.println(info[0]);
System.out.println(info[1]);
}*/
if(nomes.isEmpty()) {
out.println(user + ":" + password);
System.out.println("Novo Utilizador Autenticado.");
System.out.println("Bem Vindo!!");
}else if(nomes.contains(user)) {
bw.newLine();
if(password.equals(pass.get(nomes.indexOf(user)))) {
System.out.println("Utilizador autenticado com sucesso!");
System.out.println("Bem Vindo de Volta!!");
}
}else {
terminate();
}
bw.close();
br.close();
out.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
The error is happening in the last line on the pair[1]. It has a value but for some reason isn't seeing it.
Your text in the file is like "user:password" and you are trying to split it with ";". So pair[1] won't have any value. You should try split it with ":"
Try to access the values dynamically using index instead of hardcoded 0,1 to avoid index out of bond exception :
while ((line = br.readLine()) != null) {
String[] info = line.split(":");
int index = 0;
System.out.println(line);
while(index < info.length){
System.out.println(info[index++]);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
public void removeLine(String s) throws IOException, FileNotFoundException{
File tempFile = new File("temp.txt");
FileInputStream reader = new FileInputStream(sharkFile);
Scanner scanner = new Scanner(reader);
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile, true));
String currentLine;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
trimmedLine.equals(sharkName);
if(trimmedLine.equals(sharkName)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
scanner.close();
scanner = null;
reader.close();
writer.flush();
writer.close();
writer = null;
System.gc();
if(!sharkFile.delete()){
System.out.println("Could not delete file d");
return;
}
if(!tempFile.renameTo(sharkFile)){
System.out.println("Could not rename file");
return;
}
}
I've gone through numerous threads on stackoverflow and have implemented those changes but my file just won't delete. Appreciate the help.
The File API is notoriously weak on explaining why something fail, e.g. File.delete() simply returns a boolean, and value false cannot explain why.
Use the new Path API instead.
Also, please (PLEASE!) use try-with-resources.
Scanner is slow, so better to use BufferedReader, and for writing the lines back with newlines, use a PrintWriter.
Path sharkPath = sharkFile.toPath();
Path tempPath = Paths.get("temp.txt");
Charset cs = Charset.defaultCharset();
try (BufferedReader reader = Files.newBufferedReader(sharkPath, cs);
PrintWriter writer = new PrintWriter(Files.newBufferedWriter(tempPath, cs, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)))) {
for (String currentLine; (currentLine = reader.readLine()) != null; ) {
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
if (! trimmedLine.equals(sharkName))
writer.println(currentLine);
}
}
Files.delete(sharkPath); // throws descriptive exception if cannot delete
Files.move(tempPath, sharkPath); // throws exception if cannot move
Use below code, rename file before delete, it's appearing that you are accessing file name after delete:
try { //rename file first
tempFile.renameTo(sharkFile);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Unable to rename.");
}
try {
sharkFile.delete();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "Unable to delete.");
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
1st
import java.io.*;
import java.util.*;
public class MyFile {
public String[] readFiles(String FileName){
String[] names = new String[]{};
String line = null;
try{
FileReader fileReader = new FileReader(FileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
for(int i = 0;(line = bufferedReader.readLine()) != null;i++) {
names[i] = line;
}
bufferedReader.close();
}
catch(IOException ex){
ex.printStackTrace();
}
return names;
}
public static void write(String FileName,String[] names){
try{
FileWriter fileWriter = new FileWriter(FileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(int i = 0; i<names.length ; i++)
{
bufferedWriter.write(names[i]);
bufferedWriter.newLine();
}
bufferedWriter.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
public MyFile(){System.out.println("");}
}
2nd
public class Book{
public void displayAll(){
String[] bookNames;
String filename = "Books.txt";
bookNames = readFiles(filename);
for(int i=0;i<bookNames.length;i++)
{
System.out.println(""+bookNames[i]);
}
}
}
I'm a beginner in java and I am trying to create a program that will save and read books' name from a txt file.
but i get this error
Book.java:12: cannot find symbol
symbol: method readFiles(java.lang.String)
location:class com.acme.Book
bookNames = readFiles(filename);
^
i did tried to search but i just couldn't find any answer... and by the way not all of the code is written by me..
updated the mistkae (readFiles)
bookNames = readFile(filename);
You don't have readFile() method you have readFiles() method. s is missing in the end.
That should be
bookNames = readFiles(filename);
The method name is a plural
readFiles
not
readFile
You got
public String[] readFiles(String FileName){}
But you are calling
bookNames = readFile(filename); // readFile() ? should be readFiles()
You can do one of following to solve this
Change
bookNames = readFile(filename);
in to
bookNames = readFiles(filename);
Or
Change
public String[] readFiles(String FileName){}
in to
public String[] readFile(String FileName){}
as everyone meantion, you defined method readFiles and you are calling method readFile
Worth to meantion as wel, your method readFiles is defined in class MyFile while you are trying to access it from class Book which is impossible unless Book is inner class of MyFile (but this will be bad design).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Is it possible to get the inputStream of particular website content or it's page source into String?
For instance, I want to download the whole html tag from particular website into string or xml. Is it possible?
Yes of course you just have to do something like
public static void main(String[] args) {
URL url;
try {
// get URL content
url = new URL("http://www.mkyong.com");
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
//save to this filename
String fileName = "/users/mkyong/test.html";
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
//use FileWriter to write file
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while ((inputLine = br.readLine()) != null) {
bw.write(inputLine);
}
bw.close();
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
CREDIT : mkyong
You may want to look at guava's CharStreams class.
CharStreams.toString(new InputStreamReader(..))
will save you from writing much boilerplate code.
Here is doc
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have searched about this. All I got was xml parsing/ Sax parser. I need a program that will download xml data.
I need this for my android application development. thanks
For example i have a website localhost:8080/folder/sample.html.. How do i get a .xml file from that?
Sorry if I'm not answering the question - but is it the website content, you want to download? If positive, these are similar questions where the solution may lie:
How to get a web page's source code from Java
Get source of website in java
How do I retrieve a URL from a web site using Java?
How do you Programmatically Download a Webpage in Java
A good library to do URL Query String manipulation in Java
try this code:
public String getXmlText(String urlXml) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
String result = null;
try {
url = new URL(urlXml);
is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
result = result + line + "\n";
}
} catch (Exception e) {
return "";
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {}
}
return result;
}
Try this code
import java.net.*;
import java.io.*;
class Crawle {
public static void main(String ar[]) throws Exception {
URL url = new URL("http://www.foo.com/your_xml_file.xml");
InputStream io = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(io));
FileOutputStream fio = new FileOutputStream("file.xml");
PrintWriter pr = new PrintWriter(fio, true);
String data = "";
while ((data = br.readLine()) != null) {
pr.println(data);
}
}
}