I am beginner of java.
i am trying a write and show file.
But my txt file show another symbol.
I can not understand what my Error.
I am using this code.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
try {
FileOutputStream output=new FileOutputStream("C:\\Users\\BAPPY\\Desktop\\temp.txt");
for (int i = 0; i <=10; i++) {
output.write(i);
}
output.close();
FileInputStream input=new FileInputStream("C:\\Users\\BAPPY\\Desktop\\temp.txt");
int value;
while ((value=input.read())!=-1) {
System.out.println(value+" ");
}
input.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
my txt file did not show result why please tell me??
I think that your code is working the problem is that you are not seeing anything cause what you are writing are not understandable symbols.
Change
for (int i = 0; i <=10; i++) {
output.write(i);
}
for
for (int i = 66; i <=127; i++) {
output.write(i);
}
and tell how it goes.
I hope it helps
Related
I have a problem with my arraylist; indeed I need to fill my "list_Line" list with the data from my text file (example.txt) but after adding them to my list I can display my list but it seems empty... So did I fill in my list incorrectly or did I go about displaying its content incorrectly (I tried two different methods though) Please what do I have to do to be able to see the data in my text on the console?
Thank you.
Here is my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Search {
private String path_Fichier;
private static ArrayList<Search> list_Line = new ArrayList<>();
BufferedReader BR = null;
public Search(String pathfichier) {
// TODO Auto-generated constructor stub
this.path_Fichier=pathfichier;
}
void charge(ArrayList list_Line) {
FileReader fichier;
try {
fichier = new FileReader(this.path_Fichier);
BufferedReader BR = new BufferedReader(fichier);
String line;
while((line=BR.readLine())!=null) {
list_Line.add(line);
}
BR.close();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("File not found");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error");
}
}
void display() {
System.out.println("before");
System.out.println(list_Line);
for (Search m: list_Line) {
System.out.println(m);
System.out.println("between");
}
for (int i=0; i<list_Line.size(); i++) {
System.out.println(list_Line.get(i));
System.out.println("between");
}
System.out.println("after");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Search s = new Search("exemple.txt");
s.display();
}
}
You haven't even called charged() method. Call it and reply.
This question already has answers here:
PrintWriter append method not appending
(5 answers)
Closed 4 years ago.
I've recently made a Snake game with function that allows to store and find the best score of his. But unfortunetely it every time it saves your score into file, it deletes the previous file content. Is there any way to avoid that? As it is visible in the code below, I've made 3 methods. The first one is to save your score into a file. Last ones are to find the best score.
package matajus.snake;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Score {
private File file;
public static int score;
private static final String fileName = "BestScores.txt";
public Score() {
file = new File(fileName);
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void saveToFile() throws FileNotFoundException {
PrintWriter print = new PrintWriter(fileName);
print.println(score);
print.close();
}
public int findBestScore() {
List<Integer> lines = new ArrayList<Integer>();
Scanner input;
int bestScore = 0;
try {
input = new Scanner(file);
if(linesNumber() > 0) {
for(int i = 0; i < linesNumber(); i++) {
String readLine = input.nextLine();
int line = Integer.parseInt(readLine);
lines.add(line);
}
bestScore = Collections.max(lines);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bestScore;
}
private int linesNumber() throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
int lines = 0;
try {
while((line = reader.readLine()) != null) {
lines++;
}
} catch (Exception e) {
e.printStackTrace();
}
return lines;
}
}
PrintWritter will truncate the file: https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.lang.String)
Have a look at the proposed solution here: How to append text to an existing file in Java
I have my code. I think it's all right, but it is not. It keeps telling me at the beginning of each method that there is a ';' expected and it's also an 'illegal start of expression' with the void. I do not know how to fix it. Can someone please help me fix these errors?
Here's an example of the Errors:
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:203: error: ';' expected
void arrayList **()** throws FileNotFoundException();
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: illegal start of expression
**void** output()
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: ';' expected
void output **()**
My code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp{
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// scrubber();
//Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
void arrayList() throws FileNotFoundException();
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
//Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
// void scrubber()
// {
//
// }
//
//
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
}
You should use a Java IDE like Eclipse when programming Java, it would point out to you the most obvious mistakes in your code.
You missed a } after the while loop for your readFile() method (thanks to Sweeper for this one).
The syntax in your arrayList() method is wrong.
void arrayList() throws FileNotFoundException(); {
No semicolon at the end of this defintion, no parenthesis at the end too, you are describing the class, not a method. Here is the correct way:
void arrayList() throws FileNotFoundException {
1 useless } at the end of your class file.
Find below your code, with a proper layout and without syntax errors. Please use an IDE next time, that would avoid you an awful lot of trouble.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam ?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
}
void arrayList() throws FileNotFoundException
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
// Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
throws FileNotFoundException();
This should be
throws FileNotFoundException
and similarly in all cases.
Rather trivial. Don't just make up the syntax. Look it up.
I need to print out each letter from a text file using a list. I'm not sure where it is currently messing up.
Here is the code that I have so far. It currently only prints out the first letter from the file. For instance if the first character was "H" it would just print out the "H" and not continue with the rest of the file. I tested with multiple files to make sure it wasn't just the file I was working with. It takes the phrase from a standard .txt file.
Any help would be greatly appreciated!
package parsephrase;
/**
*
* #author Matt
*/
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
public class ParsePhrase {
private final Path filePath;
private ArrayList<String> inputList = new ArrayList<String>();
private ArrayList<Character>outputList = new ArrayList<Character>();
public ParsePhrase(String inputFile) {
filePath = Paths.get(inputFile);
}
public void readLines() {
try (Scanner input = new Scanner(filePath)) {
while (input.hasNextLine()) {
logInputLine(input.nextLine());
}
input.close();
}
catch (IOException e) {
System.out.println("Unable to access file.");
}
}
public void logInputLine(String lineIn) {
Scanner input = new Scanner(lineIn);
inputList.add(input.nextLine());
input.close();
}
public void displayOutput() {
for (int inputListIndex = 0; inputListIndex < inputList.size(); inputListIndex++) {
String inputString = inputList.get(inputListIndex);
for (int inputStringIndex = 0; inputStringIndex < inputString.length(); inputStringIndex++) {
if (outputList.isEmpty()) {
outputList.add(inputString.charAt(inputStringIndex));
continue;
}
for (int outputListIndex = 0; outputListIndex < outputList.size(); outputListIndex++) {
if (Character.isLetter(inputString.charAt(inputStringIndex))) {
if (inputString.charAt(inputStringIndex) <= outputList.get(outputListIndex));
displayCharArray(outputList);
break;
}
else if (inputString.charAt(inputStringIndex) > outputList.get(outputListIndex)) {
if (outputListIndex == outputList.size() - 1) {
outputList.add(inputString.charAt(inputStringIndex));
displayCharArray(outputList);
break;
} else {
continue;
}
}
}
}
}
}
public void displayCharArray(ArrayList<Character> listIn) {
for (Character c : listIn) {
System.out.println(c);
}
System.out.println();
}
public static void main(String[] args)throws IOException {
ParsePhrase parser = new ParsePhrase("C:\\devel\\cis210\\Week 3\\Test.txt");
parser.readLines();
parser.displayOutput();
}
}
Though not tested, yet the issue could be caused by an if condition that is currently resulting being redundant :
if (inputString.charAt(inputStringIndex) <= outputList.get(outputListIndex)); // if terminated by semi colon
displayCharArray(outputList); // display the first character
break; // executed certainly
should ideally be :
if (inputString.charAt(inputStringIndex) <= outputList.get(outputListIndex)) {
displayCharArray(outputList);
break;
}
I am trying to read an excel file and then write to csv file using xssf .I am getting out of memory error(Heap space). i see that fileinputstream is good for memory management ,but still i see the issue
package xlsxtocsv;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class xlsxtocsv
{
private static final String NEW_LINE_CHARACTER="\r\n";
/**
* Write the string into a text file
* #param csvFileName
* #param csvData
* #throws Exception
*/
private static void writeCSV(String csvFileName,String csvData) throws Exception{
FileOutputStream writer = new FileOutputStream(csvFileName);
writer.write(csvData.getBytes());
writer.close();
System.out.println("Sucessfully written data to "+csvFileName);
}
public static void excelXToCSVfile(String excelFileName,String csvFileName,String Field_Delimiter,int Sheet_Number) {
checkValidFile(excelFileName);
XSSFWorkbook myWorkBook;
try {
myWorkBook = new XSSFWorkbook(new FileInputStream(excelFileName));
XSSFSheet mySheet = myWorkBook.getSheetAt(Sheet_Number);
String csvData="";
DataFormatter formatter = new DataFormatter(Locale.US);
checkValidFile(excelFileName);
int rows = mySheet.getPhysicalNumberOfRows();
String prefix="\"";
for (int eachRow = 0;eachRow<rows;eachRow++) {
XSSFRow myRow = (XSSFRow) mySheet.getRow(eachRow);
for ( int i=0;i<myRow.getLastCellNum();i++){
if(i==0)
{
csvData += prefix+formatter.formatCellValue(myRow.getCell(i))+prefix;
}
else
{
csvData += Field_Delimiter+prefix+formatter.formatCellValue(myRow.getCell(i))+prefix;
}
}
csvData+=NEW_LINE_CHARACTER;
}
try {
writeCSV(csvFileName, csvData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* get Cell value from XLSX file column
* #param myCell
* #return
* #throws Exception
*/
private static void checkValidFile(String fileName){
boolean valid=true;
try{
File f = new File(fileName);
if ( !f.exists() || f.isDirectory() ){
valid=false;
}
}catch(Exception e){
valid=false;
}
if ( !valid){
System.out.println("File doesn't exist: " + fileName);
System.exit(0);
}
}
public static void main(String[] args) throws Exception
{
String inp_file_name="";
String Output_file_name="";
String delimiter=",";
//inp_file_name=args[0];
//Output_file_name=args[1];
enter code here
//delimiter=args[2];
inp_file_name="C:/Users/xxx/Desktop/cloudera_shared/test_data.xlsx";
Output_file_name="C:/Users/xxx/Desktop/cloudera_shared/test_data.csv";
delimiter="|";
if(args.length==4 && (args[3].equals("") == false))
{
int Sheet_Number=Integer.parseInt(args[3]);
excelXToCSVfile(inp_file_name,Output_file_name,delimiter,Sheet_Number);
}
else
{
excelXToCSVfile(inp_file_name,Output_file_name,delimiter,0);
}
}
}
You can set the max size of the heap memory available to your Java process like this (here I increase it to 1024 MB).
java -Xmx1024m -jar myProgram.jar
If you run java -X you can see the different options available.
Try running your program in a profiler to get a better idea of which parts are memory intensive.
I can suggest you the problems beyond your code:
String csvData should be replaced with StringBuffer csvData.
You can declare FileOutputStream(nameFile, true) (set append is true)
You can use the multithread to execute 2 tasks:
First: read content from your file excel.
Two: write that content which is has just read.