.doc 또는 .pdf 파일을 가져 와서 .txt로 변환하는 프로그램을 만들고 있습니다. 거기에서, 나는 자바 스캐너를 사용하여 파일을 읽고 그걸로 내가 무엇을 할 수 있습니다. .doc 및 .pdf를 변환하기 위해 나는 Runtime.getRuntime().exec("textutil")
을 사용하여 파일을 변환합니다.자바에서 mac 터미널을 통해 파일 조작하기
그러나 이름에 공백이 포함 된 파일을 변환하려고하면 문제가 발생합니다. 기본적으로 단락의 질문과 답변이 포함 된 파일을 가져 와서 한 번에 한 문장 씩 읽습니다. 완전히 우아하지는 않습니다.
//it has to do with the space in the file name, i suppose i could just rename each file i plan on using
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class AClass
{
public static void main(String[] args)
{
String fileName="/Users/name/Documents/Quizzes/Finals 1.doc"; // a default string
try
{
String s="textutil -convert txt "+correct(fileName); //see function correct
System.out.println(s); //prints the string, if I copy and paste it into terminal it DOES execute
Process proc=Runtime.getRuntime().exec(s); //executes in terminal, don't look into this... it works
} catch (Exception e) { System.out.println("Conversion failed");}
File file=new File(fileName);
Scanner reader=null;
Scanner keyboard=new Scanner(System.in);
try
{
reader=new Scanner(file);
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
System.out.println("Save the file to "+fileName);
System.exit(0);
}
System.out.println("Found the file!");
System.out.println("Hit enter to read each sentence (otherwise it will quit). \nThe program will notify you when the answer is next\n");
int qCount=0; //just a counter
while (reader.hasNext()) //not eof
{
String line=reader.nextLine().trim();
String[] sentences;
//System.out.println(line);
sentences=breakUp(line); //break up the entire line into sentences[], this //function DOES work.
for (int i=0; i<sentences.length; i++)
{
String s="";
if (!(line.equals("") || line.equals("\n")))
{
s= keyboard.nextLine(); //hit enter to see each sentence, this loop works
}
if (!s.equals("")) //quit on non-null input
{
System.out.println("Done");
System.exit(0);
}
if (sentences[i].toLowerCase().indexOf("answer") != -1) //if answer is in the sentence
{
System.out.println("\nThe answer is next, hit enter again to see it");
keyboard.nextLine();
System.out.println(sentences[i]);
qCount++;
}
else
{
int max=120; //simple formatting (output window doesn't //auto \n for lines)
if (sentences[i].length()<max)
System.out.println(sentences[i]);
else
{
for (int j=0; j<sentences[i].length(); j+=max)
{
if (j+max>sentences[i].length())
System.out.println(sentences[i].substring(j, sentences[i].length()));
else
System.out.println(sentences[i].substring(j, j+max));
}
}
}
}
}
System.out.println("End of file");
System.out.println("Total questions="+qCount);
}
public static String[] breakUp(String line) //this function works, finds periods
{
if ((line.equals("") || line.equals(null)) || line.length()<2)
return new String[] {""};
String[] tempSents=new String[500];
int count=0;
int pos=0;
int dotPos=line.indexOf(".", pos);
while (dotPos != -1 && count<tempSents.length)
{
tempSents[count]=line.substring(pos, dotPos+1);
pos=dotPos+1;
dotPos=line.indexOf(".", pos);
count++;
}
if (count==0)
return new String[] {line};
else
{
tempSents[count]=line.substring(pos);
count++;
}
return Arrays.copyOf(tempSents, count);
}
public static String correct(String s) //this function works, it adds a '\' in front of //a space so that when it is passed to the terminal it is proper syntax
{
for (int i=0; i<s.length(); i++)
{
if (s.charAt(i)==' ')
{
s=s.substring(0, i)+"\\"+s.substring(i);
i++;
if (i<=s.length())
return s.trim();
}
}
return s.trim();
}
}
내가 간부로 통과 복사하여 터미널에 붙여 넣습니다 문자열을 인쇄 할 때, 그것은 그러나 아무것도 가진 파일 (런타임 명령을 통해 발생하지, 제대로 실행 않습니다, 다시 다음은 코드입니다 이름에 공백이 있으면 다르게 작동합니다). 미리 감사드립니다.
'System.exit (0) '처럼'System.out' 대신'System.err'에 인쇄해야합니다. 그렇지 않으면 출력이 손실 될 수 있습니다. –
또한 코드를 단순화하여 코드를 보는 사람들이 오류의 원인이되는 부분 만 볼 수 있도록하십시오. –