Error at
bw.write(dataString);
How can i fix this?
dataString cannot be resolved to a variable.
public class test {
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
String dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
DeclaredataString outside of the try and catch block... Thats all. ;) If you declare it inside a loop or in this case your try catch block, its lifecycle is limited to it.
Like this:
String dataString = null;
and inside the try-catch block:
dataString = Arrays.toString(dataArray);
dataString is out of scope in the try block.
Perhaps add dataString as an instance variable at the top of your class.
public class test {
private String dataString = null;
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
...
The dataString variable's scope is limited to the first try-catch block. Change its declaration as following,
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
String dataString = null;
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
import java.io.*;
import java.util.Random;
import java.util.Scanner;
class EncryptDecryptFile{
public String readEncryptionFile()
{
String contentLine1 = "";
//String encryptFilename = Solution.filepath + "EncryptionFile.txt";
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader("C:\\Users\\HP\\Desktop\\EncryptionFile.txt"));
String contentLine = br.readLine();
while (contentLine != null)
{
contentLine1 = contentLine;
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if(br != null)
br.close();
}
catch (IOException ioe)
{
System.out.println("Error in closing the BufferedReader");
}
}
return contentLine1;
}
public void writeDecryptionFile(String message)
{
BufferedWriter bw = null;
//String decryptFilename = Solution.filepath + "DecryptionFile.txt";
try
{
File file = new File("C:\\Users\\HP\\Desktop\\DecryptionFile.txt");
if (!file.exists())
{
file.createNewFile();
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(message);
}
else
{
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(message);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if(bw!=null)
bw.close();
}
catch(Exception ex)
{
System.out.println("Error in closing the BufferedWriter"+ex);
}
}
}
}
public class Solution {
public static String filepath = "C:\\Users\\HP\\Desktop\\";
private static String generateString()
{
char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
StringBuilder generatedString = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 40; i++) {
char c = chars[random.nextInt(chars.length)];
generatedString.append(c);
}
return generatedString.toString();
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();
try{
EncryptDecryptFile f = new EncryptDecryptFile ();
String encryptFilename = Solution.filepath + "EncryptionFile.txt";
String generatedString = generateString();
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\HP\\Desktop\\EncryptionFile.txt"));
writer.write(generatedString);
writer.close();
if(f.readEncryptionFile().equals(generatedString))
{
f.writeDecryptionFile(message);
String decryptFilename = Solution.filepath + "DecryptionFile.txt";
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\HP\\Desktop\\DecryptionFile.txt"));
String messageFromFile = reader.readLine();
reader.close();
System.out.println(messageFromFile);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
When I write in the Decryption.txt file using writeDecryptionFile(message) method the file not accept the message.
There are two method readEncryptionFile() method and writeDecryptionFile(message) method.
readEncryptionFile() read the content from Encryption.txt and it matches with generatedString if it equals true then,
writeDecryptionFile(message) method write the message String message = sc.nextLine(); to the Decryption.txt file.
instead of this you can use library to decrypt and encrypt.
I'm not quite sure, what you are trying to ask, but it seem's like you are missing a 'flush' in writeDecryptionFile
...
bw = new BufferedWriter(fw);
bw.write(message);
bw.flush();
...
without the flush the buffered characters are never written to the stream
https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#flush()
I was trying to delete a line from a file. I've search on the internet. And i made a method. Here is it.
public void removeLine(BufferedReader br , File f, String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));
}
temp.renameTo(f);
bw.close();
br.close();
}
I don't know what is wrong with this method. Could you help me?
Here is where i use this method
delete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt) {
BufferedReader br = null;
try{
String enterID2 = enterID1.getText().trim();
File books = new File("books.txt");
br = new BufferedReader(new FileReader(books));
removeLine(br , books, enterID2);
System.out.println("done");
}catch (NumberFormatException e1) {
System.out.println("This is not a number");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Delete is a JButton. No error recieved.
Try this code:
public static void removeLine(BufferedReader br , File f, String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));
}
bw.close();
br.close();
boolean delete = f.delete();
boolean b = temp.renameTo(f);
}
I have a Java program that troubleshoots common problems with phones. To do this I have set up a scanner that reads the user input for any keywords. If one of these keywords is found, a method will output from a text file a solution to the problem suggested by that keyword.
My problem is that when I run the program, all the lines from the text file are outputted, from every method, disregarding my input.
Here's the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class task2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your problem?");
String input = scan.nextLine();
String[] problems = {"screen", "display", "broken", "cracked", "camera", "flash", "ports"};
String[] solutions = input.split("broken");
for(int x=0; x < problems.length; x++){
if(input.contains("broken")){
if(input.contains("screen")){
brokenScreen();
} else{
}
if(input.contains("display")) {
brokenDisplay();
} else{
}
if(input.contains("camera")) {
brokenCamera();
} else{
}
if(input.contains("flash")) {
brokenFlash();
} else{
}
if(input.contains("ports")) {
brokenPorts();
} else{
}
}
else{
}
if(input.contains("cracked")) {
if(input.contains("screen")) {
crackedScreen();
} else{
}
}
if(input.contains("water")) {
waterPhone();
}
else{
}
}
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
}
public static void noSolution() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; //Location of the text file
try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void waterPhone() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenPorts() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenFlash() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenCamera() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void crackedScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenDisplay() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can anyone please solve this issue? Any help would be greatly appreciated.
Remove
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
at the end of your main method (after the for loop).
Hello I'm creating a HangMan game and I want the array list of words to come from the internet. Its not initializing for me. Can anyone help? This is the code.
public String getaword()
{
try
{
URL url = new URL ("http://dictionary-thesaurus.com/wordlists/Adjectives%28929%29.txt");
//URLConnection urlConnection = (URLConnection)url.openConnection();
//inStream = new InputStreamReader(urlConnection.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null)
{
lines.add(str);
words = lines.toArray(new String[lines.size()]);
}
}
catch (Exception e)
{
e.getStackTrace();
}
Random r = new Random();
int num;
num = r.nextInt(words.length);
return words[num];
}
Try this.
public static void main(String[] args) {
ArrayList<String> lines = new ArrayList<String>();
try {
URL url = new URL ("http://dictionary-thesaurus.com/wordlists/Adjectives(929).txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = null;
while((str = in.readLine()) != null) {
lines.add(str);
}
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(lines);
}
I have looked around on how to do this and I keep finding different solutions, none of which has worked fine for me and I don't understand why. Does FileReader only work for local files? I tried a combination of scripts found on the site and it still doesn't quite work, it just throws an exception and leaves me with ERROR for the variable content. Here's the code I've been using unsuccessfully:
public String downloadfile(String link){
String content = "";
try {
URL url = new URL(link);
URLConnection conexion = url.openConnection();
conexion.connect();
InputStream is = url.openStream();
BufferedReader br = new BufferedReader( new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
content = sb.toString();
br.close();
is.close();
} catch (Exception e) {
content = "ERROR";
Log.e("ERROR DOWNLOADING",
"File not Found" + e.getMessage());
}
return content;
}
Use this as a downloader(provide a path to save your file(along with the extension) and the exact link of the text file)
public static void downloader(String fileName, String url) throws IOException {
File file = new File(fileName);
url = url.replace(" ", "%20");
URL website = new URL(url);
if (file.exists()) {
file.delete();
}
if (!file.exists()) {
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
}
}
Then call this function to read the text file
public static String[] read(String fileName) {
String result[] = null;
Vector v = new Vector(10, 2);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String tmp = "";
while ((tmp = br.readLine()) != null) {
v.add(tmp);
}
Iterator i = v.iterator();
result = new String[v.toArray().length];
int count = 0;
while (i.hasNext()) {
result[count++] = i.next().toString();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return (result);
}
And then finally the main method
public static void main(){
downloader("D:\\file.txt","http://www.abcd.com/textFile.txt");
String data[]=read("D:\\file.txt");
}
try this:
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder();
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
sb.append(str );
}
in.close();
String serverTextAsString = sb.toString();
} catch (MalformedURLException e) {
} catch (IOException e) {
}