Java File file = new file not working ; cannot find symbol [closed] - java

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
At the moment I'm making a HangMan GUI game in Java. It works when I put the words right into the program.
But now I want to load a textfile and create a string of it, in the code below the string content.
Here on StackOverflow I have read about the use of scanners.
Now I have this code, but it won't accept the File file = new File("woordenlijst.txt"); statement, it says at 'File' that it cannot find symbol. Can you help me? this is my code:
import java.util.Scanner;
public class galgjeGUI extends javax.swing.JFrame {
/**
* Creates new form galgjeGUI
*/
private String wGalg; // het te raden woord
private int fouten; // globale variabele toegevoegd jonp
private int pogingen;
private int levens = 7;
public galgjeGUI() {
initComponents();
buttonDisableFunction();
File file = new File("woordenlijst.txt");
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
}

how does java know what you mean by File, there is no class called File, you are looking for java.io.File so tell compiler to use that by adding
import java.io.File;

1) Import proper packages.
2) Handle exceptions.
3) close() Scanner object after usage.
import java.io.*; //import
Scanner scan = null;
try { //handle exceptions
File file = new File("woordenlijst.txt");
scan = new Scanner(file);
}
catch(FileNotFoundException e) {
System.out.println(e);
}
finally {
scan.close(); // give up the resource.
}

Related

Error Using HWPFDocument [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I have been trying to read a .doc and .docx file and assign the text in the file into a String variable in java but I keep having the error
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The type org.apache.poi.poifs.filesystem.POIFSFileSystem cannot be resolved. It is indirectly referenced from required .class files
The type org.apache.poi.poifs.filesystem.DirectoryNode cannot be resolved. It is indirectly referenced from required .class files
I have the following code to test the program
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\test.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
I have downloaded a .jar file from
https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad/3.9
I think the .jar file that I imported is incomplete. If so, can anyone give me a link for the complete library?
You need to include poi-3.15.jar into your classpath.
You can find all poi jars & dependencies as single download here
If you are using maven,
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>

Why can't I read all lines of a file in java? [closed]

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
I'm trying to make a text editor in Java, but I can't seem to get the "open file" feature to work. When I run the code, it only displays the first line of a file. I've tried all of the code snippets from: How to read a large text file line by line using Java?, but it still reads the first line only.
This is what I have tried:
JMenuItem mntmOpen = new JMenuItem("Open");
mntmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
mntmOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mntmOpen) {
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
Path HI = file.toPath();
try( Stream<String> lines = Files.lines(HI)
){
for( String line : (Iterable<String>) lines::iterator )
{
editorPane.setText(line);
}
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});
Check out this answer here, you should be able to use the section in the while loop. Pretty straight forward run until null which basically states that the buffer will continue to read until the reader sends back a null pointer in which case there is nothing left in the file. If this doesn't work then we can take a look at it again. Also you got downvoted for asking a question without searching for an answer first. https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html

Java - how to Read a properties file into array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
All - I am a newbie to java. So need some help or code
where the properties file is like
test.properties
100
200
300
400
I want to read it into an single array, so that the input data that I get, i can check if its within the array or not.
I could actually hard code the like if id=100 or id=200 or id=300 {then do somethings} else { do something ordo nothing} .
I was able to find the answer for it: Going to add the code here
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
public class read_properties_into_array {
private static List<String> sensitivePropertiesList=new ArrayList<String>();
public static void main(String[] args) {
try {
File file = new File("test.properties");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
sensitivePropertiesList.add(new String(key));
//String value = properties.getProperty(key);
//System.out.println(key);
}
System.out.println("hi I am here");
System.out.println("lenght of list:"+sensitivePropertiesList.size());
for(int i=0;i<sensitivePropertiesList.size();i++)
{
System.out.println(sensitivePropertiesList.get(i));
}
System.out.println("Check if 100 it exists.");
if (sensitivePropertiesList.contains("100"))
{
System.out.println(" 100 it exists.");
}
else
{
System.out.println(" 100 Does not exist.");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please add the test.properties file at the java project level if using eclipse.
Test.properties
100
200
300
Though your question is not clear, I think you don't need a properties class to read an array from. You put key=value pairs in a properties file.
You should first read a file using java IO, then put all values in an array and finally iterate over that array and check for your value.
Check for some code here:
https://stackoverflow.com/a/7705672/841221
If you don't use a Java Properties file, but rather something like
test.properties
100
200
300
You could read all lines into a List and work later on that list.
Path inputFile = Paths.get("test.properties");
Charset fileCharset = Charset.defaultCharset();
List<String> allValues = Files.readAllLines(inputFile, fileCharset);
// work on that list
for (String value : allValues) {
System.out.println(value);
}

How to write data to a text file in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm creating a sport prediction game for my Grade 11 year and I'm having issues writing data to a text file. I'm using NetBeans 7.3.1. I'm using a button where every time it is pressed data entered by the user must be written to the text file. The text file is empty in the beginning and I need to add data to it. After the first click on the button the data keep rewriting itself and the new data is not added. It needs to be in a new line each time. Thank you very much. Some coding would be awesome!
I just did a quick search for appending to a file (usually a good thing to do): this question seems to be what your looking for.
I haven't tested this, but this should work:
private boolean appendToFile(String fileName, String data, String lineSeparator)
throws IOException {
FileWriter writer = null;
File file = new File(fileName)
if (!file.exists()) {
file.createNewFile();
}
try {
writer = new FileWriter(fileName, true);
writer.append(data);
writer.append(lineSeparator);
} catch (IOException ioe) {
return false;
} finally {
if (writer != null) {
writer.close();
}
}
return true;
}

Adding new lines to a .txt file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm studying Chinese.
I have an iPhone app with optical character recognizer that can capture vocab lists in this format: (character TAB pronunciation TAB definition)
淫秽 TAB yin2hui4 TAB obscene; salacious; bawdy
网站 TAB wang3zhan4 TAB website
专项 TAB zhuan1xiang4 TAB attr. earmarked
but the flashcard app I use requires this format: (Character NEWLINE Pronunciation NEWLINE Definition)
淫秽
yin2hui4
obscene; salacious; bawdy
网站
wang3zhan4
<computing> website
专项
zhuan1xiang4
attr. earmarked
I only know a little Java. How do I convert the first format to the second format?
Obviously, we don't want to do your homework. But we don't want to leave you stranded either.
I've left many things open and the below is just a Java-looking pseudocode. You can start here...
FileReader reader = ... // open the file reader using the input file
FileWriter writer = ...// open a file for writing output
while(the stream doesn't end) { // provide the condition, as must be
String line = ... // read a line from the reader
String character = line.substring(0, line.indexOf("\t")),
pronounciation = line.substring(character.length() -1).substring(line.indexOf("\t", character.length()),
definition = line.substring(line.lastIndexOf("\t")); // Obviously, this isn't accurate.... you need to work around this.
writeLineToFile(character)
writeLineToFile(pronounciation)
writeLineToFile(definition)
}
close the reader and writer
Even though it looks like an Exercise. But ideally you can do.
Get the file contents (use commons-io)
Replace TAB with new line and write to file
example code
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class Test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String path = "C:/test.txt";
// TODO Auto-generated method stub
File file = new File(path);
String string = FileUtils.readFileToString(file);
String finalString = string.replaceAll("\t", "\n");
FileUtils.write(file, finalString);
}
}
The file now would look like
淫秽
yin2hui4
obscene; salacious; bawdy
网站
wang3zhan4
website
专项
zhuan1xiang4
attr. earmarked

Categories